]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/util.c
util-lib: split out user/group/uid/gid calls into user-util.[ch]
[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/oom.h>
33 #include <linux/sched.h>
34 #include <locale.h>
35 #include <netinet/ip.h>
36 #include <poll.h>
37 #include <pwd.h>
38 #include <sched.h>
39 #include <signal.h>
40 #include <stdarg.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <sys/file.h>
45 #include <sys/ioctl.h>
46 #include <sys/mman.h>
47 #include <sys/mount.h>
48 #include <sys/personality.h>
49 #include <sys/prctl.h>
50 #include <sys/resource.h>
51 #include <sys/stat.h>
52 #include <sys/statvfs.h>
53 #include <sys/time.h>
54 #include <sys/types.h>
55 #include <sys/utsname.h>
56 #include <sys/vfs.h>
57 #include <sys/wait.h>
58 #include <sys/xattr.h>
59 #include <syslog.h>
60 #include <unistd.h>
61
62 /* When we include libgen.h because we need dirname() we immediately
63 * undefine basename() since libgen.h defines it as a macro to the
64 * POSIX version which is really broken. We prefer GNU basename(). */
65 #include <libgen.h>
66 #undef basename
67
68 #ifdef HAVE_SYS_AUXV_H
69 #include <sys/auxv.h>
70 #endif
71
72 /* We include linux/fs.h as last of the system headers, as it
73 * otherwise conflicts with sys/mount.h. Yay, Linux is great! */
74 #include <linux/fs.h>
75
76 #include "build.h"
77 #include "def.h"
78 #include "device-nodes.h"
79 #include "env-util.h"
80 #include "escape.h"
81 #include "exit-status.h"
82 #include "fd-util.h"
83 #include "fileio.h"
84 #include "formats-util.h"
85 #include "gunicode.h"
86 #include "hashmap.h"
87 #include "hostname-util.h"
88 #include "ioprio.h"
89 #include "log.h"
90 #include "macro.h"
91 #include "missing.h"
92 #include "mkdir.h"
93 #include "path-util.h"
94 #include "process-util.h"
95 #include "random-util.h"
96 #include "signal-util.h"
97 #include "sparse-endian.h"
98 #include "string-util.h"
99 #include "strv.h"
100 #include "terminal-util.h"
101 #include "user-util.h"
102 #include "utf8.h"
103 #include "util.h"
104 #include "virt.h"
105
106 /* Put this test here for a lack of better place */
107 assert_cc(EAGAIN == EWOULDBLOCK);
108
109 int saved_argc = 0;
110 char **saved_argv = NULL;
111
112 size_t page_size(void) {
113 static thread_local size_t pgsz = 0;
114 long r;
115
116 if (_likely_(pgsz > 0))
117 return pgsz;
118
119 r = sysconf(_SC_PAGESIZE);
120 assert(r > 0);
121
122 pgsz = (size_t) r;
123 return pgsz;
124 }
125
126 int unlink_noerrno(const char *path) {
127 PROTECT_ERRNO;
128 int r;
129
130 r = unlink(path);
131 if (r < 0)
132 return -errno;
133
134 return 0;
135 }
136
137 int parse_boolean(const char *v) {
138 assert(v);
139
140 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
141 return 1;
142 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
143 return 0;
144
145 return -EINVAL;
146 }
147
148 int parse_pid(const char *s, pid_t* ret_pid) {
149 unsigned long ul = 0;
150 pid_t pid;
151 int r;
152
153 assert(s);
154 assert(ret_pid);
155
156 r = safe_atolu(s, &ul);
157 if (r < 0)
158 return r;
159
160 pid = (pid_t) ul;
161
162 if ((unsigned long) pid != ul)
163 return -ERANGE;
164
165 if (pid <= 0)
166 return -ERANGE;
167
168 *ret_pid = pid;
169 return 0;
170 }
171
172 int safe_atou(const char *s, unsigned *ret_u) {
173 char *x = NULL;
174 unsigned long l;
175
176 assert(s);
177 assert(ret_u);
178
179 errno = 0;
180 l = strtoul(s, &x, 0);
181
182 if (!x || x == s || *x || errno)
183 return errno > 0 ? -errno : -EINVAL;
184
185 if ((unsigned long) (unsigned) l != l)
186 return -ERANGE;
187
188 *ret_u = (unsigned) l;
189 return 0;
190 }
191
192 int safe_atoi(const char *s, int *ret_i) {
193 char *x = NULL;
194 long l;
195
196 assert(s);
197 assert(ret_i);
198
199 errno = 0;
200 l = strtol(s, &x, 0);
201
202 if (!x || x == s || *x || errno)
203 return errno > 0 ? -errno : -EINVAL;
204
205 if ((long) (int) l != l)
206 return -ERANGE;
207
208 *ret_i = (int) l;
209 return 0;
210 }
211
212 int safe_atou8(const char *s, uint8_t *ret) {
213 char *x = NULL;
214 unsigned long l;
215
216 assert(s);
217 assert(ret);
218
219 errno = 0;
220 l = strtoul(s, &x, 0);
221
222 if (!x || x == s || *x || errno)
223 return errno > 0 ? -errno : -EINVAL;
224
225 if ((unsigned long) (uint8_t) l != l)
226 return -ERANGE;
227
228 *ret = (uint8_t) l;
229 return 0;
230 }
231
232 int safe_atou16(const char *s, uint16_t *ret) {
233 char *x = NULL;
234 unsigned long l;
235
236 assert(s);
237 assert(ret);
238
239 errno = 0;
240 l = strtoul(s, &x, 0);
241
242 if (!x || x == s || *x || errno)
243 return errno > 0 ? -errno : -EINVAL;
244
245 if ((unsigned long) (uint16_t) l != l)
246 return -ERANGE;
247
248 *ret = (uint16_t) l;
249 return 0;
250 }
251
252 int safe_atoi16(const char *s, int16_t *ret) {
253 char *x = NULL;
254 long l;
255
256 assert(s);
257 assert(ret);
258
259 errno = 0;
260 l = strtol(s, &x, 0);
261
262 if (!x || x == s || *x || errno)
263 return errno > 0 ? -errno : -EINVAL;
264
265 if ((long) (int16_t) l != l)
266 return -ERANGE;
267
268 *ret = (int16_t) l;
269 return 0;
270 }
271
272 int safe_atollu(const char *s, long long unsigned *ret_llu) {
273 char *x = NULL;
274 unsigned long long l;
275
276 assert(s);
277 assert(ret_llu);
278
279 errno = 0;
280 l = strtoull(s, &x, 0);
281
282 if (!x || x == s || *x || errno)
283 return errno ? -errno : -EINVAL;
284
285 *ret_llu = l;
286 return 0;
287 }
288
289 int safe_atolli(const char *s, long long int *ret_lli) {
290 char *x = NULL;
291 long long l;
292
293 assert(s);
294 assert(ret_lli);
295
296 errno = 0;
297 l = strtoll(s, &x, 0);
298
299 if (!x || x == s || *x || errno)
300 return errno ? -errno : -EINVAL;
301
302 *ret_lli = l;
303 return 0;
304 }
305
306 int safe_atod(const char *s, double *ret_d) {
307 char *x = NULL;
308 double d = 0;
309 locale_t loc;
310
311 assert(s);
312 assert(ret_d);
313
314 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
315 if (loc == (locale_t) 0)
316 return -errno;
317
318 errno = 0;
319 d = strtod_l(s, &x, loc);
320
321 if (!x || x == s || *x || errno) {
322 freelocale(loc);
323 return errno ? -errno : -EINVAL;
324 }
325
326 freelocale(loc);
327 *ret_d = (double) d;
328 return 0;
329 }
330
331
332 int fchmod_umask(int fd, mode_t m) {
333 mode_t u;
334 int r;
335
336 u = umask(0777);
337 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
338 umask(u);
339
340 return r;
341 }
342
343 int readlinkat_malloc(int fd, const char *p, char **ret) {
344 size_t l = 100;
345 int r;
346
347 assert(p);
348 assert(ret);
349
350 for (;;) {
351 char *c;
352 ssize_t n;
353
354 c = new(char, l);
355 if (!c)
356 return -ENOMEM;
357
358 n = readlinkat(fd, p, c, l-1);
359 if (n < 0) {
360 r = -errno;
361 free(c);
362 return r;
363 }
364
365 if ((size_t) n < l-1) {
366 c[n] = 0;
367 *ret = c;
368 return 0;
369 }
370
371 free(c);
372 l *= 2;
373 }
374 }
375
376 int readlink_malloc(const char *p, char **ret) {
377 return readlinkat_malloc(AT_FDCWD, p, ret);
378 }
379
380 int readlink_value(const char *p, char **ret) {
381 _cleanup_free_ char *link = NULL;
382 char *value;
383 int r;
384
385 r = readlink_malloc(p, &link);
386 if (r < 0)
387 return r;
388
389 value = basename(link);
390 if (!value)
391 return -ENOENT;
392
393 value = strdup(value);
394 if (!value)
395 return -ENOMEM;
396
397 *ret = value;
398
399 return 0;
400 }
401
402 int readlink_and_make_absolute(const char *p, char **r) {
403 _cleanup_free_ char *target = NULL;
404 char *k;
405 int j;
406
407 assert(p);
408 assert(r);
409
410 j = readlink_malloc(p, &target);
411 if (j < 0)
412 return j;
413
414 k = file_in_same_dir(p, target);
415 if (!k)
416 return -ENOMEM;
417
418 *r = k;
419 return 0;
420 }
421
422 int readlink_and_canonicalize(const char *p, char **r) {
423 char *t, *s;
424 int j;
425
426 assert(p);
427 assert(r);
428
429 j = readlink_and_make_absolute(p, &t);
430 if (j < 0)
431 return j;
432
433 s = canonicalize_file_name(t);
434 if (s) {
435 free(t);
436 *r = s;
437 } else
438 *r = t;
439
440 path_kill_slashes(*r);
441
442 return 0;
443 }
444
445 char *file_in_same_dir(const char *path, const char *filename) {
446 char *e, *ret;
447 size_t k;
448
449 assert(path);
450 assert(filename);
451
452 /* This removes the last component of path and appends
453 * filename, unless the latter is absolute anyway or the
454 * former isn't */
455
456 if (path_is_absolute(filename))
457 return strdup(filename);
458
459 e = strrchr(path, '/');
460 if (!e)
461 return strdup(filename);
462
463 k = strlen(filename);
464 ret = new(char, (e + 1 - path) + k + 1);
465 if (!ret)
466 return NULL;
467
468 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
469 return ret;
470 }
471
472 int rmdir_parents(const char *path, const char *stop) {
473 size_t l;
474 int r = 0;
475
476 assert(path);
477 assert(stop);
478
479 l = strlen(path);
480
481 /* Skip trailing slashes */
482 while (l > 0 && path[l-1] == '/')
483 l--;
484
485 while (l > 0) {
486 char *t;
487
488 /* Skip last component */
489 while (l > 0 && path[l-1] != '/')
490 l--;
491
492 /* Skip trailing slashes */
493 while (l > 0 && path[l-1] == '/')
494 l--;
495
496 if (l <= 0)
497 break;
498
499 if (!(t = strndup(path, l)))
500 return -ENOMEM;
501
502 if (path_startswith(stop, t)) {
503 free(t);
504 return 0;
505 }
506
507 r = rmdir(t);
508 free(t);
509
510 if (r < 0)
511 if (errno != ENOENT)
512 return -errno;
513 }
514
515 return 0;
516 }
517
518 char hexchar(int x) {
519 static const char table[16] = "0123456789abcdef";
520
521 return table[x & 15];
522 }
523
524 int unhexchar(char c) {
525
526 if (c >= '0' && c <= '9')
527 return c - '0';
528
529 if (c >= 'a' && c <= 'f')
530 return c - 'a' + 10;
531
532 if (c >= 'A' && c <= 'F')
533 return c - 'A' + 10;
534
535 return -EINVAL;
536 }
537
538 char *hexmem(const void *p, size_t l) {
539 char *r, *z;
540 const uint8_t *x;
541
542 z = r = malloc(l * 2 + 1);
543 if (!r)
544 return NULL;
545
546 for (x = p; x < (const uint8_t*) p + l; x++) {
547 *(z++) = hexchar(*x >> 4);
548 *(z++) = hexchar(*x & 15);
549 }
550
551 *z = 0;
552 return r;
553 }
554
555 int unhexmem(const char *p, size_t l, void **mem, size_t *len) {
556 _cleanup_free_ uint8_t *r = NULL;
557 uint8_t *z;
558 const char *x;
559
560 assert(mem);
561 assert(len);
562 assert(p);
563
564 z = r = malloc((l + 1) / 2 + 1);
565 if (!r)
566 return -ENOMEM;
567
568 for (x = p; x < p + l; x += 2) {
569 int a, b;
570
571 a = unhexchar(x[0]);
572 if (a < 0)
573 return a;
574 else if (x+1 < p + l) {
575 b = unhexchar(x[1]);
576 if (b < 0)
577 return b;
578 } else
579 b = 0;
580
581 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
582 }
583
584 *z = 0;
585
586 *mem = r;
587 r = NULL;
588 *len = (l + 1) / 2;
589
590 return 0;
591 }
592
593 /* https://tools.ietf.org/html/rfc4648#section-6
594 * Notice that base32hex differs from base32 in the alphabet it uses.
595 * The distinction is that the base32hex representation preserves the
596 * order of the underlying data when compared as bytestrings, this is
597 * useful when representing NSEC3 hashes, as one can then verify the
598 * order of hashes directly from their representation. */
599 char base32hexchar(int x) {
600 static const char table[32] = "0123456789"
601 "ABCDEFGHIJKLMNOPQRSTUV";
602
603 return table[x & 31];
604 }
605
606 int unbase32hexchar(char c) {
607 unsigned offset;
608
609 if (c >= '0' && c <= '9')
610 return c - '0';
611
612 offset = '9' - '0' + 1;
613
614 if (c >= 'A' && c <= 'V')
615 return c - 'A' + offset;
616
617 return -EINVAL;
618 }
619
620 char *base32hexmem(const void *p, size_t l, bool padding) {
621 char *r, *z;
622 const uint8_t *x;
623 size_t len;
624
625 if (padding)
626 /* five input bytes makes eight output bytes, padding is added so we must round up */
627 len = 8 * (l + 4) / 5;
628 else {
629 /* same, but round down as there is no padding */
630 len = 8 * l / 5;
631
632 switch (l % 5) {
633 case 4:
634 len += 7;
635 break;
636 case 3:
637 len += 5;
638 break;
639 case 2:
640 len += 4;
641 break;
642 case 1:
643 len += 2;
644 break;
645 }
646 }
647
648 z = r = malloc(len + 1);
649 if (!r)
650 return NULL;
651
652 for (x = p; x < (const uint8_t*) p + (l / 5) * 5; x += 5) {
653 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
654 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
655 *(z++) = base32hexchar(x[0] >> 3); /* 000XXXXX */
656 *(z++) = base32hexchar((x[0] & 7) << 2 | x[1] >> 6); /* 000XXXYY */
657 *(z++) = base32hexchar((x[1] & 63) >> 1); /* 000YYYYY */
658 *(z++) = base32hexchar((x[1] & 1) << 4 | x[2] >> 4); /* 000YZZZZ */
659 *(z++) = base32hexchar((x[2] & 15) << 1 | x[3] >> 7); /* 000ZZZZQ */
660 *(z++) = base32hexchar((x[3] & 127) >> 2); /* 000QQQQQ */
661 *(z++) = base32hexchar((x[3] & 3) << 3 | x[4] >> 5); /* 000QQWWW */
662 *(z++) = base32hexchar((x[4] & 31)); /* 000WWWWW */
663 }
664
665 switch (l % 5) {
666 case 4:
667 *(z++) = base32hexchar(x[0] >> 3); /* 000XXXXX */
668 *(z++) = base32hexchar((x[0] & 7) << 2 | x[1] >> 6); /* 000XXXYY */
669 *(z++) = base32hexchar((x[1] & 63) >> 1); /* 000YYYYY */
670 *(z++) = base32hexchar((x[1] & 1) << 4 | x[2] >> 4); /* 000YZZZZ */
671 *(z++) = base32hexchar((x[2] & 15) << 1 | x[3] >> 7); /* 000ZZZZQ */
672 *(z++) = base32hexchar((x[3] & 127) >> 2); /* 000QQQQQ */
673 *(z++) = base32hexchar((x[3] & 3) << 3); /* 000QQ000 */
674 if (padding)
675 *(z++) = '=';
676
677 break;
678
679 case 3:
680 *(z++) = base32hexchar(x[0] >> 3); /* 000XXXXX */
681 *(z++) = base32hexchar((x[0] & 7) << 2 | x[1] >> 6); /* 000XXXYY */
682 *(z++) = base32hexchar((x[1] & 63) >> 1); /* 000YYYYY */
683 *(z++) = base32hexchar((x[1] & 1) << 4 | x[2] >> 4); /* 000YZZZZ */
684 *(z++) = base32hexchar((x[2] & 15) << 1); /* 000ZZZZ0 */
685 if (padding) {
686 *(z++) = '=';
687 *(z++) = '=';
688 *(z++) = '=';
689 }
690
691 break;
692
693 case 2:
694 *(z++) = base32hexchar(x[0] >> 3); /* 000XXXXX */
695 *(z++) = base32hexchar((x[0] & 7) << 2 | x[1] >> 6); /* 000XXXYY */
696 *(z++) = base32hexchar((x[1] & 63) >> 1); /* 000YYYYY */
697 *(z++) = base32hexchar((x[1] & 1) << 4); /* 000Y0000 */
698 if (padding) {
699 *(z++) = '=';
700 *(z++) = '=';
701 *(z++) = '=';
702 *(z++) = '=';
703 }
704
705 break;
706
707 case 1:
708 *(z++) = base32hexchar(x[0] >> 3); /* 000XXXXX */
709 *(z++) = base32hexchar((x[0] & 7) << 2); /* 000XXX00 */
710 if (padding) {
711 *(z++) = '=';
712 *(z++) = '=';
713 *(z++) = '=';
714 *(z++) = '=';
715 *(z++) = '=';
716 *(z++) = '=';
717 }
718
719 break;
720 }
721
722 *z = 0;
723 return r;
724 }
725
726 int unbase32hexmem(const char *p, size_t l, bool padding, void **mem, size_t *_len) {
727 _cleanup_free_ uint8_t *r = NULL;
728 int a, b, c, d, e, f, g, h;
729 uint8_t *z;
730 const char *x;
731 size_t len;
732 unsigned pad = 0;
733
734 assert(p);
735
736 /* padding ensures any base32hex input has input divisible by 8 */
737 if (padding && l % 8 != 0)
738 return -EINVAL;
739
740 if (padding) {
741 /* strip the padding */
742 while (l > 0 && p[l - 1] == '=' && pad < 7) {
743 pad ++;
744 l --;
745 }
746 }
747
748 /* a group of eight input bytes needs five output bytes, in case of
749 padding we need to add some extra bytes */
750 len = (l / 8) * 5;
751
752 switch (l % 8) {
753 case 7:
754 len += 4;
755 break;
756 case 5:
757 len += 3;
758 break;
759 case 4:
760 len += 2;
761 break;
762 case 2:
763 len += 1;
764 break;
765 case 0:
766 break;
767 default:
768 return -EINVAL;
769 }
770
771 z = r = malloc(len + 1);
772 if (!r)
773 return -ENOMEM;
774
775 for (x = p; x < p + (l / 8) * 8; x += 8) {
776 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
777 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
778 a = unbase32hexchar(x[0]);
779 if (a < 0)
780 return -EINVAL;
781
782 b = unbase32hexchar(x[1]);
783 if (b < 0)
784 return -EINVAL;
785
786 c = unbase32hexchar(x[2]);
787 if (c < 0)
788 return -EINVAL;
789
790 d = unbase32hexchar(x[3]);
791 if (d < 0)
792 return -EINVAL;
793
794 e = unbase32hexchar(x[4]);
795 if (e < 0)
796 return -EINVAL;
797
798 f = unbase32hexchar(x[5]);
799 if (f < 0)
800 return -EINVAL;
801
802 g = unbase32hexchar(x[6]);
803 if (g < 0)
804 return -EINVAL;
805
806 h = unbase32hexchar(x[7]);
807 if (h < 0)
808 return -EINVAL;
809
810 *(z++) = (uint8_t) a << 3 | (uint8_t) b >> 2; /* XXXXXYYY */
811 *(z++) = (uint8_t) b << 6 | (uint8_t) c << 1 | (uint8_t) d >> 4; /* YYZZZZZW */
812 *(z++) = (uint8_t) d << 4 | (uint8_t) e >> 1; /* WWWWSSSS */
813 *(z++) = (uint8_t) e << 7 | (uint8_t) f << 2 | (uint8_t) g >> 3; /* SQQQQQVV */
814 *(z++) = (uint8_t) g << 5 | (uint8_t) h; /* VVVRRRRR */
815 }
816
817 switch (l % 8) {
818 case 7:
819 a = unbase32hexchar(x[0]);
820 if (a < 0)
821 return -EINVAL;
822
823 b = unbase32hexchar(x[1]);
824 if (b < 0)
825 return -EINVAL;
826
827 c = unbase32hexchar(x[2]);
828 if (c < 0)
829 return -EINVAL;
830
831 d = unbase32hexchar(x[3]);
832 if (d < 0)
833 return -EINVAL;
834
835 e = unbase32hexchar(x[4]);
836 if (e < 0)
837 return -EINVAL;
838
839 f = unbase32hexchar(x[5]);
840 if (f < 0)
841 return -EINVAL;
842
843 g = unbase32hexchar(x[6]);
844 if (g < 0)
845 return -EINVAL;
846
847 /* g == 000VV000 */
848 if (g & 7)
849 return -EINVAL;
850
851 *(z++) = (uint8_t) a << 3 | (uint8_t) b >> 2; /* XXXXXYYY */
852 *(z++) = (uint8_t) b << 6 | (uint8_t) c << 1 | (uint8_t) d >> 4; /* YYZZZZZW */
853 *(z++) = (uint8_t) d << 4 | (uint8_t) e >> 1; /* WWWWSSSS */
854 *(z++) = (uint8_t) e << 7 | (uint8_t) f << 2 | (uint8_t) g >> 3; /* SQQQQQVV */
855
856 break;
857 case 5:
858 a = unbase32hexchar(x[0]);
859 if (a < 0)
860 return -EINVAL;
861
862 b = unbase32hexchar(x[1]);
863 if (b < 0)
864 return -EINVAL;
865
866 c = unbase32hexchar(x[2]);
867 if (c < 0)
868 return -EINVAL;
869
870 d = unbase32hexchar(x[3]);
871 if (d < 0)
872 return -EINVAL;
873
874 e = unbase32hexchar(x[4]);
875 if (e < 0)
876 return -EINVAL;
877
878 /* e == 000SSSS0 */
879 if (e & 1)
880 return -EINVAL;
881
882 *(z++) = (uint8_t) a << 3 | (uint8_t) b >> 2; /* XXXXXYYY */
883 *(z++) = (uint8_t) b << 6 | (uint8_t) c << 1 | (uint8_t) d >> 4; /* YYZZZZZW */
884 *(z++) = (uint8_t) d << 4 | (uint8_t) e >> 1; /* WWWWSSSS */
885
886 break;
887 case 4:
888 a = unbase32hexchar(x[0]);
889 if (a < 0)
890 return -EINVAL;
891
892 b = unbase32hexchar(x[1]);
893 if (b < 0)
894 return -EINVAL;
895
896 c = unbase32hexchar(x[2]);
897 if (c < 0)
898 return -EINVAL;
899
900 d = unbase32hexchar(x[3]);
901 if (d < 0)
902 return -EINVAL;
903
904 /* d == 000W0000 */
905 if (d & 15)
906 return -EINVAL;
907
908 *(z++) = (uint8_t) a << 3 | (uint8_t) b >> 2; /* XXXXXYYY */
909 *(z++) = (uint8_t) b << 6 | (uint8_t) c << 1 | (uint8_t) d >> 4; /* YYZZZZZW */
910
911 break;
912 case 2:
913 a = unbase32hexchar(x[0]);
914 if (a < 0)
915 return -EINVAL;
916
917 b = unbase32hexchar(x[1]);
918 if (b < 0)
919 return -EINVAL;
920
921 /* b == 000YYY00 */
922 if (b & 3)
923 return -EINVAL;
924
925 *(z++) = (uint8_t) a << 3 | (uint8_t) b >> 2; /* XXXXXYYY */
926
927 break;
928 case 0:
929 break;
930 default:
931 return -EINVAL;
932 }
933
934 *z = 0;
935
936 *mem = r;
937 r = NULL;
938 *_len = len;
939
940 return 0;
941 }
942
943 /* https://tools.ietf.org/html/rfc4648#section-4 */
944 char base64char(int x) {
945 static const char table[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
946 "abcdefghijklmnopqrstuvwxyz"
947 "0123456789+/";
948 return table[x & 63];
949 }
950
951 int unbase64char(char c) {
952 unsigned offset;
953
954 if (c >= 'A' && c <= 'Z')
955 return c - 'A';
956
957 offset = 'Z' - 'A' + 1;
958
959 if (c >= 'a' && c <= 'z')
960 return c - 'a' + offset;
961
962 offset += 'z' - 'a' + 1;
963
964 if (c >= '0' && c <= '9')
965 return c - '0' + offset;
966
967 offset += '9' - '0' + 1;
968
969 if (c == '+')
970 return offset;
971
972 offset ++;
973
974 if (c == '/')
975 return offset;
976
977 return -EINVAL;
978 }
979
980 char *base64mem(const void *p, size_t l) {
981 char *r, *z;
982 const uint8_t *x;
983
984 /* three input bytes makes four output bytes, padding is added so we must round up */
985 z = r = malloc(4 * (l + 2) / 3 + 1);
986 if (!r)
987 return NULL;
988
989 for (x = p; x < (const uint8_t*) p + (l / 3) * 3; x += 3) {
990 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
991 *(z++) = base64char(x[0] >> 2); /* 00XXXXXX */
992 *(z++) = base64char((x[0] & 3) << 4 | x[1] >> 4); /* 00XXYYYY */
993 *(z++) = base64char((x[1] & 15) << 2 | x[2] >> 6); /* 00YYYYZZ */
994 *(z++) = base64char(x[2] & 63); /* 00ZZZZZZ */
995 }
996
997 switch (l % 3) {
998 case 2:
999 *(z++) = base64char(x[0] >> 2); /* 00XXXXXX */
1000 *(z++) = base64char((x[0] & 3) << 4 | x[1] >> 4); /* 00XXYYYY */
1001 *(z++) = base64char((x[1] & 15) << 2); /* 00YYYY00 */
1002 *(z++) = '=';
1003
1004 break;
1005 case 1:
1006 *(z++) = base64char(x[0] >> 2); /* 00XXXXXX */
1007 *(z++) = base64char((x[0] & 3) << 4); /* 00XX0000 */
1008 *(z++) = '=';
1009 *(z++) = '=';
1010
1011 break;
1012 }
1013
1014 *z = 0;
1015 return r;
1016 }
1017
1018 int unbase64mem(const char *p, size_t l, void **mem, size_t *_len) {
1019 _cleanup_free_ uint8_t *r = NULL;
1020 int a, b, c, d;
1021 uint8_t *z;
1022 const char *x;
1023 size_t len;
1024
1025 assert(p);
1026
1027 /* padding ensures any base63 input has input divisible by 4 */
1028 if (l % 4 != 0)
1029 return -EINVAL;
1030
1031 /* strip the padding */
1032 if (l > 0 && p[l - 1] == '=')
1033 l --;
1034 if (l > 0 && p[l - 1] == '=')
1035 l --;
1036
1037 /* a group of four input bytes needs three output bytes, in case of
1038 padding we need to add two or three extra bytes */
1039 len = (l / 4) * 3 + (l % 4 ? (l % 4) - 1 : 0);
1040
1041 z = r = malloc(len + 1);
1042 if (!r)
1043 return -ENOMEM;
1044
1045 for (x = p; x < p + (l / 4) * 4; x += 4) {
1046 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1047 a = unbase64char(x[0]);
1048 if (a < 0)
1049 return -EINVAL;
1050
1051 b = unbase64char(x[1]);
1052 if (b < 0)
1053 return -EINVAL;
1054
1055 c = unbase64char(x[2]);
1056 if (c < 0)
1057 return -EINVAL;
1058
1059 d = unbase64char(x[3]);
1060 if (d < 0)
1061 return -EINVAL;
1062
1063 *(z++) = (uint8_t) a << 2 | (uint8_t) b >> 4; /* XXXXXXYY */
1064 *(z++) = (uint8_t) b << 4 | (uint8_t) c >> 2; /* YYYYZZZZ */
1065 *(z++) = (uint8_t) c << 6 | (uint8_t) d; /* ZZWWWWWW */
1066 }
1067
1068 switch (l % 4) {
1069 case 3:
1070 a = unbase64char(x[0]);
1071 if (a < 0)
1072 return -EINVAL;
1073
1074 b = unbase64char(x[1]);
1075 if (b < 0)
1076 return -EINVAL;
1077
1078 c = unbase64char(x[2]);
1079 if (c < 0)
1080 return -EINVAL;
1081
1082 /* c == 00ZZZZ00 */
1083 if (c & 3)
1084 return -EINVAL;
1085
1086 *(z++) = (uint8_t) a << 2 | (uint8_t) b >> 4; /* XXXXXXYY */
1087 *(z++) = (uint8_t) b << 4 | (uint8_t) c >> 2; /* YYYYZZZZ */
1088
1089 break;
1090 case 2:
1091 a = unbase64char(x[0]);
1092 if (a < 0)
1093 return -EINVAL;
1094
1095 b = unbase64char(x[1]);
1096 if (b < 0)
1097 return -EINVAL;
1098
1099 /* b == 00YY0000 */
1100 if (b & 15)
1101 return -EINVAL;
1102
1103 *(z++) = (uint8_t) a << 2 | (uint8_t) (b >> 4); /* XXXXXXYY */
1104
1105 break;
1106 case 0:
1107
1108 break;
1109 default:
1110 return -EINVAL;
1111 }
1112
1113 *z = 0;
1114
1115 *mem = r;
1116 r = NULL;
1117 *_len = len;
1118
1119 return 0;
1120 }
1121
1122 char octchar(int x) {
1123 return '0' + (x & 7);
1124 }
1125
1126 int unoctchar(char c) {
1127
1128 if (c >= '0' && c <= '7')
1129 return c - '0';
1130
1131 return -EINVAL;
1132 }
1133
1134 char decchar(int x) {
1135 return '0' + (x % 10);
1136 }
1137
1138 int undecchar(char c) {
1139
1140 if (c >= '0' && c <= '9')
1141 return c - '0';
1142
1143 return -EINVAL;
1144 }
1145
1146 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1147 assert(filename);
1148
1149 return
1150 filename[0] == '.' ||
1151 streq(filename, "lost+found") ||
1152 streq(filename, "aquota.user") ||
1153 streq(filename, "aquota.group") ||
1154 endswith(filename, ".rpmnew") ||
1155 endswith(filename, ".rpmsave") ||
1156 endswith(filename, ".rpmorig") ||
1157 endswith(filename, ".dpkg-old") ||
1158 endswith(filename, ".dpkg-new") ||
1159 endswith(filename, ".dpkg-tmp") ||
1160 endswith(filename, ".dpkg-dist") ||
1161 endswith(filename, ".dpkg-bak") ||
1162 endswith(filename, ".dpkg-backup") ||
1163 endswith(filename, ".dpkg-remove") ||
1164 endswith(filename, ".swp");
1165 }
1166
1167 bool hidden_file(const char *filename) {
1168 assert(filename);
1169
1170 if (endswith(filename, "~"))
1171 return true;
1172
1173 return hidden_file_allow_backup(filename);
1174 }
1175
1176 bool fstype_is_network(const char *fstype) {
1177 static const char table[] =
1178 "afs\0"
1179 "cifs\0"
1180 "smbfs\0"
1181 "sshfs\0"
1182 "ncpfs\0"
1183 "ncp\0"
1184 "nfs\0"
1185 "nfs4\0"
1186 "gfs\0"
1187 "gfs2\0"
1188 "glusterfs\0";
1189
1190 const char *x;
1191
1192 x = startswith(fstype, "fuse.");
1193 if (x)
1194 fstype = x;
1195
1196 return nulstr_contains(table, fstype);
1197 }
1198
1199 int parse_size(const char *t, uint64_t base, uint64_t *size) {
1200
1201 /* Soo, sometimes we want to parse IEC binary suffixes, and
1202 * sometimes SI decimal suffixes. This function can parse
1203 * both. Which one is the right way depends on the
1204 * context. Wikipedia suggests that SI is customary for
1205 * hardware metrics and network speeds, while IEC is
1206 * customary for most data sizes used by software and volatile
1207 * (RAM) memory. Hence be careful which one you pick!
1208 *
1209 * In either case we use just K, M, G as suffix, and not Ki,
1210 * Mi, Gi or so (as IEC would suggest). That's because that's
1211 * frickin' ugly. But this means you really need to make sure
1212 * to document which base you are parsing when you use this
1213 * call. */
1214
1215 struct table {
1216 const char *suffix;
1217 unsigned long long factor;
1218 };
1219
1220 static const struct table iec[] = {
1221 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1222 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1223 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1224 { "G", 1024ULL*1024ULL*1024ULL },
1225 { "M", 1024ULL*1024ULL },
1226 { "K", 1024ULL },
1227 { "B", 1ULL },
1228 { "", 1ULL },
1229 };
1230
1231 static const struct table si[] = {
1232 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1233 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1234 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1235 { "G", 1000ULL*1000ULL*1000ULL },
1236 { "M", 1000ULL*1000ULL },
1237 { "K", 1000ULL },
1238 { "B", 1ULL },
1239 { "", 1ULL },
1240 };
1241
1242 const struct table *table;
1243 const char *p;
1244 unsigned long long r = 0;
1245 unsigned n_entries, start_pos = 0;
1246
1247 assert(t);
1248 assert(base == 1000 || base == 1024);
1249 assert(size);
1250
1251 if (base == 1000) {
1252 table = si;
1253 n_entries = ELEMENTSOF(si);
1254 } else {
1255 table = iec;
1256 n_entries = ELEMENTSOF(iec);
1257 }
1258
1259 p = t;
1260 do {
1261 unsigned long long l, tmp;
1262 double frac = 0;
1263 char *e;
1264 unsigned i;
1265
1266 p += strspn(p, WHITESPACE);
1267 if (*p == '-')
1268 return -ERANGE;
1269
1270 errno = 0;
1271 l = strtoull(p, &e, 10);
1272 if (errno > 0)
1273 return -errno;
1274 if (e == p)
1275 return -EINVAL;
1276
1277 if (*e == '.') {
1278 e++;
1279
1280 /* strtoull() itself would accept space/+/- */
1281 if (*e >= '0' && *e <= '9') {
1282 unsigned long long l2;
1283 char *e2;
1284
1285 l2 = strtoull(e, &e2, 10);
1286 if (errno > 0)
1287 return -errno;
1288
1289 /* Ignore failure. E.g. 10.M is valid */
1290 frac = l2;
1291 for (; e < e2; e++)
1292 frac /= 10;
1293 }
1294 }
1295
1296 e += strspn(e, WHITESPACE);
1297
1298 for (i = start_pos; i < n_entries; i++)
1299 if (startswith(e, table[i].suffix))
1300 break;
1301
1302 if (i >= n_entries)
1303 return -EINVAL;
1304
1305 if (l + (frac > 0) > ULLONG_MAX / table[i].factor)
1306 return -ERANGE;
1307
1308 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
1309 if (tmp > ULLONG_MAX - r)
1310 return -ERANGE;
1311
1312 r += tmp;
1313 if ((unsigned long long) (uint64_t) r != r)
1314 return -ERANGE;
1315
1316 p = e + strlen(table[i].suffix);
1317
1318 start_pos = i + 1;
1319
1320 } while (*p);
1321
1322 *size = r;
1323
1324 return 0;
1325 }
1326
1327 bool is_device_path(const char *path) {
1328
1329 /* Returns true on paths that refer to a device, either in
1330 * sysfs or in /dev */
1331
1332 return
1333 path_startswith(path, "/dev/") ||
1334 path_startswith(path, "/sys/");
1335 }
1336
1337 int dir_is_empty(const char *path) {
1338 _cleanup_closedir_ DIR *d;
1339 struct dirent *de;
1340
1341 d = opendir(path);
1342 if (!d)
1343 return -errno;
1344
1345 FOREACH_DIRENT(de, d, return -errno)
1346 return 0;
1347
1348 return 1;
1349 }
1350
1351 char* dirname_malloc(const char *path) {
1352 char *d, *dir, *dir2;
1353
1354 d = strdup(path);
1355 if (!d)
1356 return NULL;
1357 dir = dirname(d);
1358 assert(dir);
1359
1360 if (dir != d) {
1361 dir2 = strdup(dir);
1362 free(d);
1363 return dir2;
1364 }
1365
1366 return dir;
1367 }
1368
1369 void rename_process(const char name[8]) {
1370 assert(name);
1371
1372 /* This is a like a poor man's setproctitle(). It changes the
1373 * comm field, argv[0], and also the glibc's internally used
1374 * name of the process. For the first one a limit of 16 chars
1375 * applies, to the second one usually one of 10 (i.e. length
1376 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1377 * "systemd"). If you pass a longer string it will be
1378 * truncated */
1379
1380 prctl(PR_SET_NAME, name);
1381
1382 if (program_invocation_name)
1383 strncpy(program_invocation_name, name, strlen(program_invocation_name));
1384
1385 if (saved_argc > 0) {
1386 int i;
1387
1388 if (saved_argv[0])
1389 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
1390
1391 for (i = 1; i < saved_argc; i++) {
1392 if (!saved_argv[i])
1393 break;
1394
1395 memzero(saved_argv[i], strlen(saved_argv[i]));
1396 }
1397 }
1398 }
1399
1400 bool is_fs_type(const struct statfs *s, statfs_f_type_t magic_value) {
1401 assert(s);
1402 assert_cc(sizeof(statfs_f_type_t) >= sizeof(s->f_type));
1403
1404 return F_TYPE_EQUAL(s->f_type, magic_value);
1405 }
1406
1407 int fd_check_fstype(int fd, statfs_f_type_t magic_value) {
1408 struct statfs s;
1409
1410 if (fstatfs(fd, &s) < 0)
1411 return -errno;
1412
1413 return is_fs_type(&s, magic_value);
1414 }
1415
1416 int path_check_fstype(const char *path, statfs_f_type_t magic_value) {
1417 _cleanup_close_ int fd = -1;
1418
1419 fd = open(path, O_RDONLY);
1420 if (fd < 0)
1421 return -errno;
1422
1423 return fd_check_fstype(fd, magic_value);
1424 }
1425
1426 bool is_temporary_fs(const struct statfs *s) {
1427 return is_fs_type(s, TMPFS_MAGIC) ||
1428 is_fs_type(s, RAMFS_MAGIC);
1429 }
1430
1431 int fd_is_temporary_fs(int fd) {
1432 struct statfs s;
1433
1434 if (fstatfs(fd, &s) < 0)
1435 return -errno;
1436
1437 return is_temporary_fs(&s);
1438 }
1439
1440 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1441 assert(path);
1442
1443 /* Under the assumption that we are running privileged we
1444 * first change the access mode and only then hand out
1445 * ownership to avoid a window where access is too open. */
1446
1447 if (mode != MODE_INVALID)
1448 if (chmod(path, mode) < 0)
1449 return -errno;
1450
1451 if (uid != UID_INVALID || gid != GID_INVALID)
1452 if (chown(path, uid, gid) < 0)
1453 return -errno;
1454
1455 return 0;
1456 }
1457
1458 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
1459 assert(fd >= 0);
1460
1461 /* Under the assumption that we are running privileged we
1462 * first change the access mode and only then hand out
1463 * ownership to avoid a window where access is too open. */
1464
1465 if (mode != MODE_INVALID)
1466 if (fchmod(fd, mode) < 0)
1467 return -errno;
1468
1469 if (uid != UID_INVALID || gid != GID_INVALID)
1470 if (fchown(fd, uid, gid) < 0)
1471 return -errno;
1472
1473 return 0;
1474 }
1475
1476 int files_same(const char *filea, const char *fileb) {
1477 struct stat a, b;
1478
1479 if (stat(filea, &a) < 0)
1480 return -errno;
1481
1482 if (stat(fileb, &b) < 0)
1483 return -errno;
1484
1485 return a.st_dev == b.st_dev &&
1486 a.st_ino == b.st_ino;
1487 }
1488
1489 int running_in_chroot(void) {
1490 int ret;
1491
1492 ret = files_same("/proc/1/root", "/");
1493 if (ret < 0)
1494 return ret;
1495
1496 return ret == 0;
1497 }
1498
1499 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
1500 _cleanup_close_ int fd;
1501 int r;
1502
1503 assert(path);
1504
1505 if (parents)
1506 mkdir_parents(path, 0755);
1507
1508 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
1509 if (fd < 0)
1510 return -errno;
1511
1512 if (mode > 0) {
1513 r = fchmod(fd, mode);
1514 if (r < 0)
1515 return -errno;
1516 }
1517
1518 if (uid != UID_INVALID || gid != GID_INVALID) {
1519 r = fchown(fd, uid, gid);
1520 if (r < 0)
1521 return -errno;
1522 }
1523
1524 if (stamp != USEC_INFINITY) {
1525 struct timespec ts[2];
1526
1527 timespec_store(&ts[0], stamp);
1528 ts[1] = ts[0];
1529 r = futimens(fd, ts);
1530 } else
1531 r = futimens(fd, NULL);
1532 if (r < 0)
1533 return -errno;
1534
1535 return 0;
1536 }
1537
1538 int touch(const char *path) {
1539 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
1540 }
1541
1542 static char *unquote(const char *s, const char* quotes) {
1543 size_t l;
1544 assert(s);
1545
1546 /* This is rather stupid, simply removes the heading and
1547 * trailing quotes if there is one. Doesn't care about
1548 * escaping or anything.
1549 *
1550 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
1551
1552 l = strlen(s);
1553 if (l < 2)
1554 return strdup(s);
1555
1556 if (strchr(quotes, s[0]) && s[l-1] == s[0])
1557 return strndup(s+1, l-2);
1558
1559 return strdup(s);
1560 }
1561
1562 noreturn void freeze(void) {
1563
1564 /* Make sure nobody waits for us on a socket anymore */
1565 close_all_fds(NULL, 0);
1566
1567 sync();
1568
1569 for (;;)
1570 pause();
1571 }
1572
1573 bool null_or_empty(struct stat *st) {
1574 assert(st);
1575
1576 if (S_ISREG(st->st_mode) && st->st_size <= 0)
1577 return true;
1578
1579 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
1580 return true;
1581
1582 return false;
1583 }
1584
1585 int null_or_empty_path(const char *fn) {
1586 struct stat st;
1587
1588 assert(fn);
1589
1590 if (stat(fn, &st) < 0)
1591 return -errno;
1592
1593 return null_or_empty(&st);
1594 }
1595
1596 int null_or_empty_fd(int fd) {
1597 struct stat st;
1598
1599 assert(fd >= 0);
1600
1601 if (fstat(fd, &st) < 0)
1602 return -errno;
1603
1604 return null_or_empty(&st);
1605 }
1606
1607 DIR *xopendirat(int fd, const char *name, int flags) {
1608 int nfd;
1609 DIR *d;
1610
1611 assert(!(flags & O_CREAT));
1612
1613 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
1614 if (nfd < 0)
1615 return NULL;
1616
1617 d = fdopendir(nfd);
1618 if (!d) {
1619 safe_close(nfd);
1620 return NULL;
1621 }
1622
1623 return d;
1624 }
1625
1626 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
1627 _cleanup_free_ char *t = NULL, *u = NULL;
1628 size_t enc_len;
1629
1630 u = unquote(tagvalue, QUOTES);
1631 if (!u)
1632 return NULL;
1633
1634 enc_len = strlen(u) * 4 + 1;
1635 t = new(char, enc_len);
1636 if (!t)
1637 return NULL;
1638
1639 if (encode_devnode_name(u, t, enc_len) < 0)
1640 return NULL;
1641
1642 return strjoin("/dev/disk/by-", by, "/", t, NULL);
1643 }
1644
1645 char *fstab_node_to_udev_node(const char *p) {
1646 assert(p);
1647
1648 if (startswith(p, "LABEL="))
1649 return tag_to_udev_node(p+6, "label");
1650
1651 if (startswith(p, "UUID="))
1652 return tag_to_udev_node(p+5, "uuid");
1653
1654 if (startswith(p, "PARTUUID="))
1655 return tag_to_udev_node(p+9, "partuuid");
1656
1657 if (startswith(p, "PARTLABEL="))
1658 return tag_to_udev_node(p+10, "partlabel");
1659
1660 return strdup(p);
1661 }
1662
1663 bool dirent_is_file(const struct dirent *de) {
1664 assert(de);
1665
1666 if (hidden_file(de->d_name))
1667 return false;
1668
1669 if (de->d_type != DT_REG &&
1670 de->d_type != DT_LNK &&
1671 de->d_type != DT_UNKNOWN)
1672 return false;
1673
1674 return true;
1675 }
1676
1677 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
1678 assert(de);
1679
1680 if (de->d_type != DT_REG &&
1681 de->d_type != DT_LNK &&
1682 de->d_type != DT_UNKNOWN)
1683 return false;
1684
1685 if (hidden_file_allow_backup(de->d_name))
1686 return false;
1687
1688 return endswith(de->d_name, suffix);
1689 }
1690
1691 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
1692 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
1693 _cleanup_set_free_free_ Set *seen = NULL;
1694 char **directory;
1695
1696 /* We fork this all off from a child process so that we can
1697 * somewhat cleanly make use of SIGALRM to set a time limit */
1698
1699 (void) reset_all_signal_handlers();
1700 (void) reset_signal_mask();
1701
1702 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
1703
1704 pids = hashmap_new(NULL);
1705 if (!pids)
1706 return log_oom();
1707
1708 seen = set_new(&string_hash_ops);
1709 if (!seen)
1710 return log_oom();
1711
1712 STRV_FOREACH(directory, directories) {
1713 _cleanup_closedir_ DIR *d;
1714 struct dirent *de;
1715
1716 d = opendir(*directory);
1717 if (!d) {
1718 if (errno == ENOENT)
1719 continue;
1720
1721 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
1722 }
1723
1724 FOREACH_DIRENT(de, d, break) {
1725 _cleanup_free_ char *path = NULL;
1726 pid_t pid;
1727 int r;
1728
1729 if (!dirent_is_file(de))
1730 continue;
1731
1732 if (set_contains(seen, de->d_name)) {
1733 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
1734 continue;
1735 }
1736
1737 r = set_put_strdup(seen, de->d_name);
1738 if (r < 0)
1739 return log_oom();
1740
1741 path = strjoin(*directory, "/", de->d_name, NULL);
1742 if (!path)
1743 return log_oom();
1744
1745 if (null_or_empty_path(path)) {
1746 log_debug("%s is empty (a mask).", path);
1747 continue;
1748 }
1749
1750 pid = fork();
1751 if (pid < 0) {
1752 log_error_errno(errno, "Failed to fork: %m");
1753 continue;
1754 } else if (pid == 0) {
1755 char *_argv[2];
1756
1757 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
1758
1759 if (!argv) {
1760 _argv[0] = path;
1761 _argv[1] = NULL;
1762 argv = _argv;
1763 } else
1764 argv[0] = path;
1765
1766 execv(path, argv);
1767 return log_error_errno(errno, "Failed to execute %s: %m", path);
1768 }
1769
1770 log_debug("Spawned %s as " PID_FMT ".", path, pid);
1771
1772 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
1773 if (r < 0)
1774 return log_oom();
1775 path = NULL;
1776 }
1777 }
1778
1779 /* Abort execution of this process after the timout. We simply
1780 * rely on SIGALRM as default action terminating the process,
1781 * and turn on alarm(). */
1782
1783 if (timeout != USEC_INFINITY)
1784 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
1785
1786 while (!hashmap_isempty(pids)) {
1787 _cleanup_free_ char *path = NULL;
1788 pid_t pid;
1789
1790 pid = PTR_TO_UINT(hashmap_first_key(pids));
1791 assert(pid > 0);
1792
1793 path = hashmap_remove(pids, UINT_TO_PTR(pid));
1794 assert(path);
1795
1796 wait_for_terminate_and_warn(path, pid, true);
1797 }
1798
1799 return 0;
1800 }
1801
1802 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
1803 pid_t executor_pid;
1804 int r;
1805 char *name;
1806 char **dirs = (char**) directories;
1807
1808 assert(!strv_isempty(dirs));
1809
1810 name = basename(dirs[0]);
1811 assert(!isempty(name));
1812
1813 /* Executes all binaries in the directories in parallel and waits
1814 * for them to finish. Optionally a timeout is applied. If a file
1815 * with the same name exists in more than one directory, the
1816 * earliest one wins. */
1817
1818 executor_pid = fork();
1819 if (executor_pid < 0) {
1820 log_error_errno(errno, "Failed to fork: %m");
1821 return;
1822
1823 } else if (executor_pid == 0) {
1824 r = do_execute(dirs, timeout, argv);
1825 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
1826 }
1827
1828 wait_for_terminate_and_warn(name, executor_pid, true);
1829 }
1830
1831 bool plymouth_running(void) {
1832 return access("/run/plymouth/pid", F_OK) >= 0;
1833 }
1834
1835 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1836 FILE *f;
1837 char *t;
1838 int r, fd;
1839
1840 assert(path);
1841 assert(_f);
1842 assert(_temp_path);
1843
1844 r = tempfn_xxxxxx(path, NULL, &t);
1845 if (r < 0)
1846 return r;
1847
1848 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
1849 if (fd < 0) {
1850 free(t);
1851 return -errno;
1852 }
1853
1854 f = fdopen(fd, "we");
1855 if (!f) {
1856 unlink_noerrno(t);
1857 free(t);
1858 safe_close(fd);
1859 return -errno;
1860 }
1861
1862 *_f = f;
1863 *_temp_path = t;
1864
1865 return 0;
1866 }
1867
1868 int symlink_atomic(const char *from, const char *to) {
1869 _cleanup_free_ char *t = NULL;
1870 int r;
1871
1872 assert(from);
1873 assert(to);
1874
1875 r = tempfn_random(to, NULL, &t);
1876 if (r < 0)
1877 return r;
1878
1879 if (symlink(from, t) < 0)
1880 return -errno;
1881
1882 if (rename(t, to) < 0) {
1883 unlink_noerrno(t);
1884 return -errno;
1885 }
1886
1887 return 0;
1888 }
1889
1890 int symlink_idempotent(const char *from, const char *to) {
1891 _cleanup_free_ char *p = NULL;
1892 int r;
1893
1894 assert(from);
1895 assert(to);
1896
1897 if (symlink(from, to) < 0) {
1898 if (errno != EEXIST)
1899 return -errno;
1900
1901 r = readlink_malloc(to, &p);
1902 if (r < 0)
1903 return r;
1904
1905 if (!streq(p, from))
1906 return -EINVAL;
1907 }
1908
1909 return 0;
1910 }
1911
1912 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
1913 _cleanup_free_ char *t = NULL;
1914 int r;
1915
1916 assert(path);
1917
1918 r = tempfn_random(path, NULL, &t);
1919 if (r < 0)
1920 return r;
1921
1922 if (mknod(t, mode, dev) < 0)
1923 return -errno;
1924
1925 if (rename(t, path) < 0) {
1926 unlink_noerrno(t);
1927 return -errno;
1928 }
1929
1930 return 0;
1931 }
1932
1933 int mkfifo_atomic(const char *path, mode_t mode) {
1934 _cleanup_free_ char *t = NULL;
1935 int r;
1936
1937 assert(path);
1938
1939 r = tempfn_random(path, NULL, &t);
1940 if (r < 0)
1941 return r;
1942
1943 if (mkfifo(t, mode) < 0)
1944 return -errno;
1945
1946 if (rename(t, path) < 0) {
1947 unlink_noerrno(t);
1948 return -errno;
1949 }
1950
1951 return 0;
1952 }
1953
1954 bool display_is_local(const char *display) {
1955 assert(display);
1956
1957 return
1958 display[0] == ':' &&
1959 display[1] >= '0' &&
1960 display[1] <= '9';
1961 }
1962
1963 int socket_from_display(const char *display, char **path) {
1964 size_t k;
1965 char *f, *c;
1966
1967 assert(display);
1968 assert(path);
1969
1970 if (!display_is_local(display))
1971 return -EINVAL;
1972
1973 k = strspn(display+1, "0123456789");
1974
1975 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
1976 if (!f)
1977 return -ENOMEM;
1978
1979 c = stpcpy(f, "/tmp/.X11-unix/X");
1980 memcpy(c, display+1, k);
1981 c[k] = 0;
1982
1983 *path = f;
1984
1985 return 0;
1986 }
1987
1988 int glob_exists(const char *path) {
1989 _cleanup_globfree_ glob_t g = {};
1990 int k;
1991
1992 assert(path);
1993
1994 errno = 0;
1995 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
1996
1997 if (k == GLOB_NOMATCH)
1998 return 0;
1999 else if (k == GLOB_NOSPACE)
2000 return -ENOMEM;
2001 else if (k == 0)
2002 return !strv_isempty(g.gl_pathv);
2003 else
2004 return errno ? -errno : -EIO;
2005 }
2006
2007 int glob_extend(char ***strv, const char *path) {
2008 _cleanup_globfree_ glob_t g = {};
2009 int k;
2010 char **p;
2011
2012 errno = 0;
2013 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
2014
2015 if (k == GLOB_NOMATCH)
2016 return -ENOENT;
2017 else if (k == GLOB_NOSPACE)
2018 return -ENOMEM;
2019 else if (k != 0 || strv_isempty(g.gl_pathv))
2020 return errno ? -errno : -EIO;
2021
2022 STRV_FOREACH(p, g.gl_pathv) {
2023 k = strv_extend(strv, *p);
2024 if (k < 0)
2025 break;
2026 }
2027
2028 return k;
2029 }
2030
2031 int dirent_ensure_type(DIR *d, struct dirent *de) {
2032 struct stat st;
2033
2034 assert(d);
2035 assert(de);
2036
2037 if (de->d_type != DT_UNKNOWN)
2038 return 0;
2039
2040 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
2041 return -errno;
2042
2043 de->d_type =
2044 S_ISREG(st.st_mode) ? DT_REG :
2045 S_ISDIR(st.st_mode) ? DT_DIR :
2046 S_ISLNK(st.st_mode) ? DT_LNK :
2047 S_ISFIFO(st.st_mode) ? DT_FIFO :
2048 S_ISSOCK(st.st_mode) ? DT_SOCK :
2049 S_ISCHR(st.st_mode) ? DT_CHR :
2050 S_ISBLK(st.st_mode) ? DT_BLK :
2051 DT_UNKNOWN;
2052
2053 return 0;
2054 }
2055
2056 int get_files_in_directory(const char *path, char ***list) {
2057 _cleanup_closedir_ DIR *d = NULL;
2058 size_t bufsize = 0, n = 0;
2059 _cleanup_strv_free_ char **l = NULL;
2060
2061 assert(path);
2062
2063 /* Returns all files in a directory in *list, and the number
2064 * of files as return value. If list is NULL returns only the
2065 * number. */
2066
2067 d = opendir(path);
2068 if (!d)
2069 return -errno;
2070
2071 for (;;) {
2072 struct dirent *de;
2073
2074 errno = 0;
2075 de = readdir(d);
2076 if (!de && errno != 0)
2077 return -errno;
2078 if (!de)
2079 break;
2080
2081 dirent_ensure_type(d, de);
2082
2083 if (!dirent_is_file(de))
2084 continue;
2085
2086 if (list) {
2087 /* one extra slot is needed for the terminating NULL */
2088 if (!GREEDY_REALLOC(l, bufsize, n + 2))
2089 return -ENOMEM;
2090
2091 l[n] = strdup(de->d_name);
2092 if (!l[n])
2093 return -ENOMEM;
2094
2095 l[++n] = NULL;
2096 } else
2097 n++;
2098 }
2099
2100 if (list) {
2101 *list = l;
2102 l = NULL; /* avoid freeing */
2103 }
2104
2105 return n;
2106 }
2107
2108 bool is_main_thread(void) {
2109 static thread_local int cached = 0;
2110
2111 if (_unlikely_(cached == 0))
2112 cached = getpid() == gettid() ? 1 : -1;
2113
2114 return cached > 0;
2115 }
2116
2117 int block_get_whole_disk(dev_t d, dev_t *ret) {
2118 char *p, *s;
2119 int r;
2120 unsigned n, m;
2121
2122 assert(ret);
2123
2124 /* If it has a queue this is good enough for us */
2125 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
2126 return -ENOMEM;
2127
2128 r = access(p, F_OK);
2129 free(p);
2130
2131 if (r >= 0) {
2132 *ret = d;
2133 return 0;
2134 }
2135
2136 /* If it is a partition find the originating device */
2137 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
2138 return -ENOMEM;
2139
2140 r = access(p, F_OK);
2141 free(p);
2142
2143 if (r < 0)
2144 return -ENOENT;
2145
2146 /* Get parent dev_t */
2147 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
2148 return -ENOMEM;
2149
2150 r = read_one_line_file(p, &s);
2151 free(p);
2152
2153 if (r < 0)
2154 return r;
2155
2156 r = sscanf(s, "%u:%u", &m, &n);
2157 free(s);
2158
2159 if (r != 2)
2160 return -EINVAL;
2161
2162 /* Only return this if it is really good enough for us. */
2163 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
2164 return -ENOMEM;
2165
2166 r = access(p, F_OK);
2167 free(p);
2168
2169 if (r >= 0) {
2170 *ret = makedev(m, n);
2171 return 0;
2172 }
2173
2174 return -ENOENT;
2175 }
2176
2177 static const char *const ioprio_class_table[] = {
2178 [IOPRIO_CLASS_NONE] = "none",
2179 [IOPRIO_CLASS_RT] = "realtime",
2180 [IOPRIO_CLASS_BE] = "best-effort",
2181 [IOPRIO_CLASS_IDLE] = "idle"
2182 };
2183
2184 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
2185
2186 static const char *const sigchld_code_table[] = {
2187 [CLD_EXITED] = "exited",
2188 [CLD_KILLED] = "killed",
2189 [CLD_DUMPED] = "dumped",
2190 [CLD_TRAPPED] = "trapped",
2191 [CLD_STOPPED] = "stopped",
2192 [CLD_CONTINUED] = "continued",
2193 };
2194
2195 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2196
2197 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
2198 [LOG_FAC(LOG_KERN)] = "kern",
2199 [LOG_FAC(LOG_USER)] = "user",
2200 [LOG_FAC(LOG_MAIL)] = "mail",
2201 [LOG_FAC(LOG_DAEMON)] = "daemon",
2202 [LOG_FAC(LOG_AUTH)] = "auth",
2203 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2204 [LOG_FAC(LOG_LPR)] = "lpr",
2205 [LOG_FAC(LOG_NEWS)] = "news",
2206 [LOG_FAC(LOG_UUCP)] = "uucp",
2207 [LOG_FAC(LOG_CRON)] = "cron",
2208 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2209 [LOG_FAC(LOG_FTP)] = "ftp",
2210 [LOG_FAC(LOG_LOCAL0)] = "local0",
2211 [LOG_FAC(LOG_LOCAL1)] = "local1",
2212 [LOG_FAC(LOG_LOCAL2)] = "local2",
2213 [LOG_FAC(LOG_LOCAL3)] = "local3",
2214 [LOG_FAC(LOG_LOCAL4)] = "local4",
2215 [LOG_FAC(LOG_LOCAL5)] = "local5",
2216 [LOG_FAC(LOG_LOCAL6)] = "local6",
2217 [LOG_FAC(LOG_LOCAL7)] = "local7"
2218 };
2219
2220 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
2221
2222 bool log_facility_unshifted_is_valid(int facility) {
2223 return facility >= 0 && facility <= LOG_FAC(~0);
2224 }
2225
2226 static const char *const log_level_table[] = {
2227 [LOG_EMERG] = "emerg",
2228 [LOG_ALERT] = "alert",
2229 [LOG_CRIT] = "crit",
2230 [LOG_ERR] = "err",
2231 [LOG_WARNING] = "warning",
2232 [LOG_NOTICE] = "notice",
2233 [LOG_INFO] = "info",
2234 [LOG_DEBUG] = "debug"
2235 };
2236
2237 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
2238
2239 bool log_level_is_valid(int level) {
2240 return level >= 0 && level <= LOG_DEBUG;
2241 }
2242
2243 static const char* const sched_policy_table[] = {
2244 [SCHED_OTHER] = "other",
2245 [SCHED_BATCH] = "batch",
2246 [SCHED_IDLE] = "idle",
2247 [SCHED_FIFO] = "fifo",
2248 [SCHED_RR] = "rr"
2249 };
2250
2251 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
2252
2253 static const char* const rlimit_table[_RLIMIT_MAX] = {
2254 [RLIMIT_CPU] = "LimitCPU",
2255 [RLIMIT_FSIZE] = "LimitFSIZE",
2256 [RLIMIT_DATA] = "LimitDATA",
2257 [RLIMIT_STACK] = "LimitSTACK",
2258 [RLIMIT_CORE] = "LimitCORE",
2259 [RLIMIT_RSS] = "LimitRSS",
2260 [RLIMIT_NOFILE] = "LimitNOFILE",
2261 [RLIMIT_AS] = "LimitAS",
2262 [RLIMIT_NPROC] = "LimitNPROC",
2263 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2264 [RLIMIT_LOCKS] = "LimitLOCKS",
2265 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2266 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2267 [RLIMIT_NICE] = "LimitNICE",
2268 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2269 [RLIMIT_RTTIME] = "LimitRTTIME"
2270 };
2271
2272 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
2273
2274 static const char* const ip_tos_table[] = {
2275 [IPTOS_LOWDELAY] = "low-delay",
2276 [IPTOS_THROUGHPUT] = "throughput",
2277 [IPTOS_RELIABILITY] = "reliability",
2278 [IPTOS_LOWCOST] = "low-cost",
2279 };
2280
2281 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
2282
2283 bool kexec_loaded(void) {
2284 bool loaded = false;
2285 char *s;
2286
2287 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
2288 if (s[0] == '1')
2289 loaded = true;
2290 free(s);
2291 }
2292 return loaded;
2293 }
2294
2295 int prot_from_flags(int flags) {
2296
2297 switch (flags & O_ACCMODE) {
2298
2299 case O_RDONLY:
2300 return PROT_READ;
2301
2302 case O_WRONLY:
2303 return PROT_WRITE;
2304
2305 case O_RDWR:
2306 return PROT_READ|PROT_WRITE;
2307
2308 default:
2309 return -EINVAL;
2310 }
2311 }
2312
2313 char *format_bytes(char *buf, size_t l, uint64_t t) {
2314 unsigned i;
2315
2316 static const struct {
2317 const char *suffix;
2318 uint64_t factor;
2319 } table[] = {
2320 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2321 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2322 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2323 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
2324 { "M", UINT64_C(1024)*UINT64_C(1024) },
2325 { "K", UINT64_C(1024) },
2326 };
2327
2328 if (t == (uint64_t) -1)
2329 return NULL;
2330
2331 for (i = 0; i < ELEMENTSOF(table); i++) {
2332
2333 if (t >= table[i].factor) {
2334 snprintf(buf, l,
2335 "%" PRIu64 ".%" PRIu64 "%s",
2336 t / table[i].factor,
2337 ((t*UINT64_C(10)) / table[i].factor) % UINT64_C(10),
2338 table[i].suffix);
2339
2340 goto finish;
2341 }
2342 }
2343
2344 snprintf(buf, l, "%" PRIu64 "B", t);
2345
2346 finish:
2347 buf[l-1] = 0;
2348 return buf;
2349
2350 }
2351
2352 void* memdup(const void *p, size_t l) {
2353 void *r;
2354
2355 assert(p);
2356
2357 r = malloc(l);
2358 if (!r)
2359 return NULL;
2360
2361 memcpy(r, p, l);
2362 return r;
2363 }
2364
2365 int fd_inc_sndbuf(int fd, size_t n) {
2366 int r, value;
2367 socklen_t l = sizeof(value);
2368
2369 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
2370 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
2371 return 0;
2372
2373 /* If we have the privileges we will ignore the kernel limit. */
2374
2375 value = (int) n;
2376 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
2377 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
2378 return -errno;
2379
2380 return 1;
2381 }
2382
2383 int fd_inc_rcvbuf(int fd, size_t n) {
2384 int r, value;
2385 socklen_t l = sizeof(value);
2386
2387 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
2388 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
2389 return 0;
2390
2391 /* If we have the privileges we will ignore the kernel limit. */
2392
2393 value = (int) n;
2394 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
2395 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
2396 return -errno;
2397 return 1;
2398 }
2399
2400 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
2401 bool stdout_is_tty, stderr_is_tty;
2402 pid_t parent_pid, agent_pid;
2403 sigset_t ss, saved_ss;
2404 unsigned n, i;
2405 va_list ap;
2406 char **l;
2407
2408 assert(pid);
2409 assert(path);
2410
2411 /* Spawns a temporary TTY agent, making sure it goes away when
2412 * we go away */
2413
2414 parent_pid = getpid();
2415
2416 /* First we temporarily block all signals, so that the new
2417 * child has them blocked initially. This way, we can be sure
2418 * that SIGTERMs are not lost we might send to the agent. */
2419 assert_se(sigfillset(&ss) >= 0);
2420 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
2421
2422 agent_pid = fork();
2423 if (agent_pid < 0) {
2424 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
2425 return -errno;
2426 }
2427
2428 if (agent_pid != 0) {
2429 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
2430 *pid = agent_pid;
2431 return 0;
2432 }
2433
2434 /* In the child:
2435 *
2436 * Make sure the agent goes away when the parent dies */
2437 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
2438 _exit(EXIT_FAILURE);
2439
2440 /* Make sure we actually can kill the agent, if we need to, in
2441 * case somebody invoked us from a shell script that trapped
2442 * SIGTERM or so... */
2443 (void) reset_all_signal_handlers();
2444 (void) reset_signal_mask();
2445
2446 /* Check whether our parent died before we were able
2447 * to set the death signal and unblock the signals */
2448 if (getppid() != parent_pid)
2449 _exit(EXIT_SUCCESS);
2450
2451 /* Don't leak fds to the agent */
2452 close_all_fds(except, n_except);
2453
2454 stdout_is_tty = isatty(STDOUT_FILENO);
2455 stderr_is_tty = isatty(STDERR_FILENO);
2456
2457 if (!stdout_is_tty || !stderr_is_tty) {
2458 int fd;
2459
2460 /* Detach from stdout/stderr. and reopen
2461 * /dev/tty for them. This is important to
2462 * ensure that when systemctl is started via
2463 * popen() or a similar call that expects to
2464 * read EOF we actually do generate EOF and
2465 * not delay this indefinitely by because we
2466 * keep an unused copy of stdin around. */
2467 fd = open("/dev/tty", O_WRONLY);
2468 if (fd < 0) {
2469 log_error_errno(errno, "Failed to open /dev/tty: %m");
2470 _exit(EXIT_FAILURE);
2471 }
2472
2473 if (!stdout_is_tty)
2474 dup2(fd, STDOUT_FILENO);
2475
2476 if (!stderr_is_tty)
2477 dup2(fd, STDERR_FILENO);
2478
2479 if (fd > 2)
2480 close(fd);
2481 }
2482
2483 /* Count arguments */
2484 va_start(ap, path);
2485 for (n = 0; va_arg(ap, char*); n++)
2486 ;
2487 va_end(ap);
2488
2489 /* Allocate strv */
2490 l = alloca(sizeof(char *) * (n + 1));
2491
2492 /* Fill in arguments */
2493 va_start(ap, path);
2494 for (i = 0; i <= n; i++)
2495 l[i] = va_arg(ap, char*);
2496 va_end(ap);
2497
2498 execv(path, l);
2499 _exit(EXIT_FAILURE);
2500 }
2501
2502 int setrlimit_closest(int resource, const struct rlimit *rlim) {
2503 struct rlimit highest, fixed;
2504
2505 assert(rlim);
2506
2507 if (setrlimit(resource, rlim) >= 0)
2508 return 0;
2509
2510 if (errno != EPERM)
2511 return -errno;
2512
2513 /* So we failed to set the desired setrlimit, then let's try
2514 * to get as close as we can */
2515 assert_se(getrlimit(resource, &highest) == 0);
2516
2517 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
2518 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
2519
2520 if (setrlimit(resource, &fixed) < 0)
2521 return -errno;
2522
2523 return 0;
2524 }
2525
2526 bool http_etag_is_valid(const char *etag) {
2527 if (isempty(etag))
2528 return false;
2529
2530 if (!endswith(etag, "\""))
2531 return false;
2532
2533 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
2534 return false;
2535
2536 return true;
2537 }
2538
2539 bool http_url_is_valid(const char *url) {
2540 const char *p;
2541
2542 if (isempty(url))
2543 return false;
2544
2545 p = startswith(url, "http://");
2546 if (!p)
2547 p = startswith(url, "https://");
2548 if (!p)
2549 return false;
2550
2551 if (isempty(p))
2552 return false;
2553
2554 return ascii_is_valid(p);
2555 }
2556
2557 bool documentation_url_is_valid(const char *url) {
2558 const char *p;
2559
2560 if (isempty(url))
2561 return false;
2562
2563 if (http_url_is_valid(url))
2564 return true;
2565
2566 p = startswith(url, "file:/");
2567 if (!p)
2568 p = startswith(url, "info:");
2569 if (!p)
2570 p = startswith(url, "man:");
2571
2572 if (isempty(p))
2573 return false;
2574
2575 return ascii_is_valid(p);
2576 }
2577
2578 bool in_initrd(void) {
2579 static int saved = -1;
2580 struct statfs s;
2581
2582 if (saved >= 0)
2583 return saved;
2584
2585 /* We make two checks here:
2586 *
2587 * 1. the flag file /etc/initrd-release must exist
2588 * 2. the root file system must be a memory file system
2589 *
2590 * The second check is extra paranoia, since misdetecting an
2591 * initrd can have bad bad consequences due the initrd
2592 * emptying when transititioning to the main systemd.
2593 */
2594
2595 saved = access("/etc/initrd-release", F_OK) >= 0 &&
2596 statfs("/", &s) >= 0 &&
2597 is_temporary_fs(&s);
2598
2599 return saved;
2600 }
2601
2602 bool filename_is_valid(const char *p) {
2603
2604 if (isempty(p))
2605 return false;
2606
2607 if (strchr(p, '/'))
2608 return false;
2609
2610 if (streq(p, "."))
2611 return false;
2612
2613 if (streq(p, ".."))
2614 return false;
2615
2616 if (strlen(p) > FILENAME_MAX)
2617 return false;
2618
2619 return true;
2620 }
2621
2622 bool string_is_safe(const char *p) {
2623 const char *t;
2624
2625 if (!p)
2626 return false;
2627
2628 for (t = p; *t; t++) {
2629 if (*t > 0 && *t < ' ')
2630 return false;
2631
2632 if (strchr("\\\"\'\x7f", *t))
2633 return false;
2634 }
2635
2636 return true;
2637 }
2638
2639 bool path_is_safe(const char *p) {
2640
2641 if (isempty(p))
2642 return false;
2643
2644 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
2645 return false;
2646
2647 if (strlen(p)+1 > PATH_MAX)
2648 return false;
2649
2650 /* The following two checks are not really dangerous, but hey, they still are confusing */
2651 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
2652 return false;
2653
2654 if (strstr(p, "//"))
2655 return false;
2656
2657 return true;
2658 }
2659
2660 /* hey glibc, APIs with callbacks without a user pointer are so useless */
2661 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
2662 int (*compar) (const void *, const void *, void *), void *arg) {
2663 size_t l, u, idx;
2664 const void *p;
2665 int comparison;
2666
2667 l = 0;
2668 u = nmemb;
2669 while (l < u) {
2670 idx = (l + u) / 2;
2671 p = (void *)(((const char *) base) + (idx * size));
2672 comparison = compar(key, p, arg);
2673 if (comparison < 0)
2674 u = idx;
2675 else if (comparison > 0)
2676 l = idx + 1;
2677 else
2678 return (void *)p;
2679 }
2680 return NULL;
2681 }
2682
2683 void init_gettext(void) {
2684 setlocale(LC_ALL, "");
2685 textdomain(GETTEXT_PACKAGE);
2686 }
2687
2688 bool is_locale_utf8(void) {
2689 const char *set;
2690 static int cached_answer = -1;
2691
2692 if (cached_answer >= 0)
2693 goto out;
2694
2695 if (!setlocale(LC_ALL, "")) {
2696 cached_answer = true;
2697 goto out;
2698 }
2699
2700 set = nl_langinfo(CODESET);
2701 if (!set) {
2702 cached_answer = true;
2703 goto out;
2704 }
2705
2706 if (streq(set, "UTF-8")) {
2707 cached_answer = true;
2708 goto out;
2709 }
2710
2711 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
2712 * unset and everything can do to UTF-8 nowadays. */
2713 set = setlocale(LC_CTYPE, NULL);
2714 if (!set) {
2715 cached_answer = true;
2716 goto out;
2717 }
2718
2719 /* Check result, but ignore the result if C was set
2720 * explicitly. */
2721 cached_answer =
2722 STR_IN_SET(set, "C", "POSIX") &&
2723 !getenv("LC_ALL") &&
2724 !getenv("LC_CTYPE") &&
2725 !getenv("LANG");
2726
2727 out:
2728 return (bool) cached_answer;
2729 }
2730
2731 const char *draw_special_char(DrawSpecialChar ch) {
2732 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
2733
2734 /* UTF-8 */ {
2735 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
2736 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
2737 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
2738 [DRAW_TREE_SPACE] = " ", /* */
2739 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
2740 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
2741 [DRAW_ARROW] = "\342\206\222", /* → */
2742 [DRAW_DASH] = "\342\200\223", /* – */
2743 },
2744
2745 /* ASCII fallback */ {
2746 [DRAW_TREE_VERTICAL] = "| ",
2747 [DRAW_TREE_BRANCH] = "|-",
2748 [DRAW_TREE_RIGHT] = "`-",
2749 [DRAW_TREE_SPACE] = " ",
2750 [DRAW_TRIANGULAR_BULLET] = ">",
2751 [DRAW_BLACK_CIRCLE] = "*",
2752 [DRAW_ARROW] = "->",
2753 [DRAW_DASH] = "-",
2754 }
2755 };
2756
2757 return draw_table[!is_locale_utf8()][ch];
2758 }
2759
2760 int on_ac_power(void) {
2761 bool found_offline = false, found_online = false;
2762 _cleanup_closedir_ DIR *d = NULL;
2763
2764 d = opendir("/sys/class/power_supply");
2765 if (!d)
2766 return errno == ENOENT ? true : -errno;
2767
2768 for (;;) {
2769 struct dirent *de;
2770 _cleanup_close_ int fd = -1, device = -1;
2771 char contents[6];
2772 ssize_t n;
2773
2774 errno = 0;
2775 de = readdir(d);
2776 if (!de && errno != 0)
2777 return -errno;
2778
2779 if (!de)
2780 break;
2781
2782 if (hidden_file(de->d_name))
2783 continue;
2784
2785 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
2786 if (device < 0) {
2787 if (errno == ENOENT || errno == ENOTDIR)
2788 continue;
2789
2790 return -errno;
2791 }
2792
2793 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2794 if (fd < 0) {
2795 if (errno == ENOENT)
2796 continue;
2797
2798 return -errno;
2799 }
2800
2801 n = read(fd, contents, sizeof(contents));
2802 if (n < 0)
2803 return -errno;
2804
2805 if (n != 6 || memcmp(contents, "Mains\n", 6))
2806 continue;
2807
2808 safe_close(fd);
2809 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2810 if (fd < 0) {
2811 if (errno == ENOENT)
2812 continue;
2813
2814 return -errno;
2815 }
2816
2817 n = read(fd, contents, sizeof(contents));
2818 if (n < 0)
2819 return -errno;
2820
2821 if (n != 2 || contents[1] != '\n')
2822 return -EIO;
2823
2824 if (contents[0] == '1') {
2825 found_online = true;
2826 break;
2827 } else if (contents[0] == '0')
2828 found_offline = true;
2829 else
2830 return -EIO;
2831 }
2832
2833 return found_online || !found_offline;
2834 }
2835
2836 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
2837 char **i;
2838
2839 assert(path);
2840 assert(mode);
2841 assert(_f);
2842
2843 if (!path_strv_resolve_uniq(search, root))
2844 return -ENOMEM;
2845
2846 STRV_FOREACH(i, search) {
2847 _cleanup_free_ char *p = NULL;
2848 FILE *f;
2849
2850 if (root)
2851 p = strjoin(root, *i, "/", path, NULL);
2852 else
2853 p = strjoin(*i, "/", path, NULL);
2854 if (!p)
2855 return -ENOMEM;
2856
2857 f = fopen(p, mode);
2858 if (f) {
2859 *_f = f;
2860 return 0;
2861 }
2862
2863 if (errno != ENOENT)
2864 return -errno;
2865 }
2866
2867 return -ENOENT;
2868 }
2869
2870 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
2871 _cleanup_strv_free_ char **copy = NULL;
2872
2873 assert(path);
2874 assert(mode);
2875 assert(_f);
2876
2877 if (path_is_absolute(path)) {
2878 FILE *f;
2879
2880 f = fopen(path, mode);
2881 if (f) {
2882 *_f = f;
2883 return 0;
2884 }
2885
2886 return -errno;
2887 }
2888
2889 copy = strv_copy((char**) search);
2890 if (!copy)
2891 return -ENOMEM;
2892
2893 return search_and_fopen_internal(path, mode, root, copy, _f);
2894 }
2895
2896 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
2897 _cleanup_strv_free_ char **s = NULL;
2898
2899 if (path_is_absolute(path)) {
2900 FILE *f;
2901
2902 f = fopen(path, mode);
2903 if (f) {
2904 *_f = f;
2905 return 0;
2906 }
2907
2908 return -errno;
2909 }
2910
2911 s = strv_split_nulstr(search);
2912 if (!s)
2913 return -ENOMEM;
2914
2915 return search_and_fopen_internal(path, mode, root, s, _f);
2916 }
2917
2918 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
2919 size_t a, newalloc;
2920 void *q;
2921
2922 assert(p);
2923 assert(allocated);
2924
2925 if (*allocated >= need)
2926 return *p;
2927
2928 newalloc = MAX(need * 2, 64u / size);
2929 a = newalloc * size;
2930
2931 /* check for overflows */
2932 if (a < size * need)
2933 return NULL;
2934
2935 q = realloc(*p, a);
2936 if (!q)
2937 return NULL;
2938
2939 *p = q;
2940 *allocated = newalloc;
2941 return q;
2942 }
2943
2944 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
2945 size_t prev;
2946 uint8_t *q;
2947
2948 assert(p);
2949 assert(allocated);
2950
2951 prev = *allocated;
2952
2953 q = greedy_realloc(p, allocated, need, size);
2954 if (!q)
2955 return NULL;
2956
2957 if (*allocated > prev)
2958 memzero(q + prev * size, (*allocated - prev) * size);
2959
2960 return q;
2961 }
2962
2963 bool id128_is_valid(const char *s) {
2964 size_t i, l;
2965
2966 l = strlen(s);
2967 if (l == 32) {
2968
2969 /* Simple formatted 128bit hex string */
2970
2971 for (i = 0; i < l; i++) {
2972 char c = s[i];
2973
2974 if (!(c >= '0' && c <= '9') &&
2975 !(c >= 'a' && c <= 'z') &&
2976 !(c >= 'A' && c <= 'Z'))
2977 return false;
2978 }
2979
2980 } else if (l == 36) {
2981
2982 /* Formatted UUID */
2983
2984 for (i = 0; i < l; i++) {
2985 char c = s[i];
2986
2987 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
2988 if (c != '-')
2989 return false;
2990 } else {
2991 if (!(c >= '0' && c <= '9') &&
2992 !(c >= 'a' && c <= 'z') &&
2993 !(c >= 'A' && c <= 'Z'))
2994 return false;
2995 }
2996 }
2997
2998 } else
2999 return false;
3000
3001 return true;
3002 }
3003
3004 int shall_restore_state(void) {
3005 _cleanup_free_ char *value = NULL;
3006 int r;
3007
3008 r = get_proc_cmdline_key("systemd.restore_state=", &value);
3009 if (r < 0)
3010 return r;
3011 if (r == 0)
3012 return true;
3013
3014 return parse_boolean(value) != 0;
3015 }
3016
3017 int proc_cmdline(char **ret) {
3018 assert(ret);
3019
3020 if (detect_container() > 0)
3021 return get_process_cmdline(1, 0, false, ret);
3022 else
3023 return read_one_line_file("/proc/cmdline", ret);
3024 }
3025
3026 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
3027 _cleanup_free_ char *line = NULL;
3028 const char *p;
3029 int r;
3030
3031 assert(parse_item);
3032
3033 r = proc_cmdline(&line);
3034 if (r < 0)
3035 return r;
3036
3037 p = line;
3038 for (;;) {
3039 _cleanup_free_ char *word = NULL;
3040 char *value = NULL;
3041
3042 r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES|EXTRACT_RELAX);
3043 if (r < 0)
3044 return r;
3045 if (r == 0)
3046 break;
3047
3048 /* Filter out arguments that are intended only for the
3049 * initrd */
3050 if (!in_initrd() && startswith(word, "rd."))
3051 continue;
3052
3053 value = strchr(word, '=');
3054 if (value)
3055 *(value++) = 0;
3056
3057 r = parse_item(word, value);
3058 if (r < 0)
3059 return r;
3060 }
3061
3062 return 0;
3063 }
3064
3065 int get_proc_cmdline_key(const char *key, char **value) {
3066 _cleanup_free_ char *line = NULL, *ret = NULL;
3067 bool found = false;
3068 const char *p;
3069 int r;
3070
3071 assert(key);
3072
3073 r = proc_cmdline(&line);
3074 if (r < 0)
3075 return r;
3076
3077 p = line;
3078 for (;;) {
3079 _cleanup_free_ char *word = NULL;
3080 const char *e;
3081
3082 r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES|EXTRACT_RELAX);
3083 if (r < 0)
3084 return r;
3085 if (r == 0)
3086 break;
3087
3088 /* Filter out arguments that are intended only for the
3089 * initrd */
3090 if (!in_initrd() && startswith(word, "rd."))
3091 continue;
3092
3093 if (value) {
3094 e = startswith(word, key);
3095 if (!e)
3096 continue;
3097
3098 r = free_and_strdup(&ret, e);
3099 if (r < 0)
3100 return r;
3101
3102 found = true;
3103 } else {
3104 if (streq(word, key))
3105 found = true;
3106 }
3107 }
3108
3109 if (value) {
3110 *value = ret;
3111 ret = NULL;
3112 }
3113
3114 return found;
3115
3116 }
3117
3118 int container_get_leader(const char *machine, pid_t *pid) {
3119 _cleanup_free_ char *s = NULL, *class = NULL;
3120 const char *p;
3121 pid_t leader;
3122 int r;
3123
3124 assert(machine);
3125 assert(pid);
3126
3127 if (!machine_name_is_valid(machine))
3128 return -EINVAL;
3129
3130 p = strjoina("/run/systemd/machines/", machine);
3131 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
3132 if (r == -ENOENT)
3133 return -EHOSTDOWN;
3134 if (r < 0)
3135 return r;
3136 if (!s)
3137 return -EIO;
3138
3139 if (!streq_ptr(class, "container"))
3140 return -EIO;
3141
3142 r = parse_pid(s, &leader);
3143 if (r < 0)
3144 return r;
3145 if (leader <= 1)
3146 return -EIO;
3147
3148 *pid = leader;
3149 return 0;
3150 }
3151
3152 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *userns_fd, int *root_fd) {
3153 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1, usernsfd = -1;
3154 int rfd = -1;
3155
3156 assert(pid >= 0);
3157
3158 if (mntns_fd) {
3159 const char *mntns;
3160
3161 mntns = procfs_file_alloca(pid, "ns/mnt");
3162 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
3163 if (mntnsfd < 0)
3164 return -errno;
3165 }
3166
3167 if (pidns_fd) {
3168 const char *pidns;
3169
3170 pidns = procfs_file_alloca(pid, "ns/pid");
3171 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
3172 if (pidnsfd < 0)
3173 return -errno;
3174 }
3175
3176 if (netns_fd) {
3177 const char *netns;
3178
3179 netns = procfs_file_alloca(pid, "ns/net");
3180 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
3181 if (netnsfd < 0)
3182 return -errno;
3183 }
3184
3185 if (userns_fd) {
3186 const char *userns;
3187
3188 userns = procfs_file_alloca(pid, "ns/user");
3189 usernsfd = open(userns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
3190 if (usernsfd < 0 && errno != ENOENT)
3191 return -errno;
3192 }
3193
3194 if (root_fd) {
3195 const char *root;
3196
3197 root = procfs_file_alloca(pid, "root");
3198 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
3199 if (rfd < 0)
3200 return -errno;
3201 }
3202
3203 if (pidns_fd)
3204 *pidns_fd = pidnsfd;
3205
3206 if (mntns_fd)
3207 *mntns_fd = mntnsfd;
3208
3209 if (netns_fd)
3210 *netns_fd = netnsfd;
3211
3212 if (userns_fd)
3213 *userns_fd = usernsfd;
3214
3215 if (root_fd)
3216 *root_fd = rfd;
3217
3218 pidnsfd = mntnsfd = netnsfd = usernsfd = -1;
3219
3220 return 0;
3221 }
3222
3223 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int userns_fd, int root_fd) {
3224 if (userns_fd >= 0) {
3225 /* Can't setns to your own userns, since then you could
3226 * escalate from non-root to root in your own namespace, so
3227 * check if namespaces equal before attempting to enter. */
3228 _cleanup_free_ char *userns_fd_path = NULL;
3229 int r;
3230 if (asprintf(&userns_fd_path, "/proc/self/fd/%d", userns_fd) < 0)
3231 return -ENOMEM;
3232
3233 r = files_same(userns_fd_path, "/proc/self/ns/user");
3234 if (r < 0)
3235 return r;
3236 if (r)
3237 userns_fd = -1;
3238 }
3239
3240 if (pidns_fd >= 0)
3241 if (setns(pidns_fd, CLONE_NEWPID) < 0)
3242 return -errno;
3243
3244 if (mntns_fd >= 0)
3245 if (setns(mntns_fd, CLONE_NEWNS) < 0)
3246 return -errno;
3247
3248 if (netns_fd >= 0)
3249 if (setns(netns_fd, CLONE_NEWNET) < 0)
3250 return -errno;
3251
3252 if (userns_fd >= 0)
3253 if (setns(userns_fd, CLONE_NEWUSER) < 0)
3254 return -errno;
3255
3256 if (root_fd >= 0) {
3257 if (fchdir(root_fd) < 0)
3258 return -errno;
3259
3260 if (chroot(".") < 0)
3261 return -errno;
3262 }
3263
3264 return reset_uid_gid();
3265 }
3266
3267 int getpeercred(int fd, struct ucred *ucred) {
3268 socklen_t n = sizeof(struct ucred);
3269 struct ucred u;
3270 int r;
3271
3272 assert(fd >= 0);
3273 assert(ucred);
3274
3275 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
3276 if (r < 0)
3277 return -errno;
3278
3279 if (n != sizeof(struct ucred))
3280 return -EIO;
3281
3282 /* Check if the data is actually useful and not suppressed due
3283 * to namespacing issues */
3284 if (u.pid <= 0)
3285 return -ENODATA;
3286 if (u.uid == UID_INVALID)
3287 return -ENODATA;
3288 if (u.gid == GID_INVALID)
3289 return -ENODATA;
3290
3291 *ucred = u;
3292 return 0;
3293 }
3294
3295 int getpeersec(int fd, char **ret) {
3296 socklen_t n = 64;
3297 char *s;
3298 int r;
3299
3300 assert(fd >= 0);
3301 assert(ret);
3302
3303 s = new0(char, n);
3304 if (!s)
3305 return -ENOMEM;
3306
3307 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
3308 if (r < 0) {
3309 free(s);
3310
3311 if (errno != ERANGE)
3312 return -errno;
3313
3314 s = new0(char, n);
3315 if (!s)
3316 return -ENOMEM;
3317
3318 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
3319 if (r < 0) {
3320 free(s);
3321 return -errno;
3322 }
3323 }
3324
3325 if (isempty(s)) {
3326 free(s);
3327 return -EOPNOTSUPP;
3328 }
3329
3330 *ret = s;
3331 return 0;
3332 }
3333
3334 /* This is much like like mkostemp() but is subject to umask(). */
3335 int mkostemp_safe(char *pattern, int flags) {
3336 _cleanup_umask_ mode_t u;
3337 int fd;
3338
3339 assert(pattern);
3340
3341 u = umask(077);
3342
3343 fd = mkostemp(pattern, flags);
3344 if (fd < 0)
3345 return -errno;
3346
3347 return fd;
3348 }
3349
3350 int open_tmpfile(const char *path, int flags) {
3351 char *p;
3352 int fd;
3353
3354 assert(path);
3355
3356 #ifdef O_TMPFILE
3357 /* Try O_TMPFILE first, if it is supported */
3358 fd = open(path, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
3359 if (fd >= 0)
3360 return fd;
3361 #endif
3362
3363 /* Fall back to unguessable name + unlinking */
3364 p = strjoina(path, "/systemd-tmp-XXXXXX");
3365
3366 fd = mkostemp_safe(p, flags);
3367 if (fd < 0)
3368 return fd;
3369
3370 unlink(p);
3371 return fd;
3372 }
3373
3374 int fd_warn_permissions(const char *path, int fd) {
3375 struct stat st;
3376
3377 if (fstat(fd, &st) < 0)
3378 return -errno;
3379
3380 if (st.st_mode & 0111)
3381 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
3382
3383 if (st.st_mode & 0002)
3384 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
3385
3386 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
3387 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);
3388
3389 return 0;
3390 }
3391
3392 unsigned long personality_from_string(const char *p) {
3393
3394 /* Parse a personality specifier. We introduce our own
3395 * identifiers that indicate specific ABIs, rather than just
3396 * hints regarding the register size, since we want to keep
3397 * things open for multiple locally supported ABIs for the
3398 * same register size. We try to reuse the ABI identifiers
3399 * used by libseccomp. */
3400
3401 #if defined(__x86_64__)
3402
3403 if (streq(p, "x86"))
3404 return PER_LINUX32;
3405
3406 if (streq(p, "x86-64"))
3407 return PER_LINUX;
3408
3409 #elif defined(__i386__)
3410
3411 if (streq(p, "x86"))
3412 return PER_LINUX;
3413
3414 #elif defined(__s390x__)
3415
3416 if (streq(p, "s390"))
3417 return PER_LINUX32;
3418
3419 if (streq(p, "s390x"))
3420 return PER_LINUX;
3421
3422 #elif defined(__s390__)
3423
3424 if (streq(p, "s390"))
3425 return PER_LINUX;
3426 #endif
3427
3428 return PERSONALITY_INVALID;
3429 }
3430
3431 const char* personality_to_string(unsigned long p) {
3432
3433 #if defined(__x86_64__)
3434
3435 if (p == PER_LINUX32)
3436 return "x86";
3437
3438 if (p == PER_LINUX)
3439 return "x86-64";
3440
3441 #elif defined(__i386__)
3442
3443 if (p == PER_LINUX)
3444 return "x86";
3445
3446 #elif defined(__s390x__)
3447
3448 if (p == PER_LINUX)
3449 return "s390x";
3450
3451 if (p == PER_LINUX32)
3452 return "s390";
3453
3454 #elif defined(__s390__)
3455
3456 if (p == PER_LINUX)
3457 return "s390";
3458
3459 #endif
3460
3461 return NULL;
3462 }
3463
3464 uint64_t physical_memory(void) {
3465 long mem;
3466
3467 /* We return this as uint64_t in case we are running as 32bit
3468 * process on a 64bit kernel with huge amounts of memory */
3469
3470 mem = sysconf(_SC_PHYS_PAGES);
3471 assert(mem > 0);
3472
3473 return (uint64_t) mem * (uint64_t) page_size();
3474 }
3475
3476 void hexdump(FILE *f, const void *p, size_t s) {
3477 const uint8_t *b = p;
3478 unsigned n = 0;
3479
3480 assert(s == 0 || b);
3481
3482 while (s > 0) {
3483 size_t i;
3484
3485 fprintf(f, "%04x ", n);
3486
3487 for (i = 0; i < 16; i++) {
3488
3489 if (i >= s)
3490 fputs(" ", f);
3491 else
3492 fprintf(f, "%02x ", b[i]);
3493
3494 if (i == 7)
3495 fputc(' ', f);
3496 }
3497
3498 fputc(' ', f);
3499
3500 for (i = 0; i < 16; i++) {
3501
3502 if (i >= s)
3503 fputc(' ', f);
3504 else
3505 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
3506 }
3507
3508 fputc('\n', f);
3509
3510 if (s < 16)
3511 break;
3512
3513 n += 16;
3514 b += 16;
3515 s -= 16;
3516 }
3517 }
3518
3519 int update_reboot_param_file(const char *param) {
3520 int r = 0;
3521
3522 if (param) {
3523 r = write_string_file(REBOOT_PARAM_FILE, param, WRITE_STRING_FILE_CREATE);
3524 if (r < 0)
3525 return log_error_errno(r, "Failed to write reboot param to "REBOOT_PARAM_FILE": %m");
3526 } else
3527 (void) unlink(REBOOT_PARAM_FILE);
3528
3529 return 0;
3530 }
3531
3532 int umount_recursive(const char *prefix, int flags) {
3533 bool again;
3534 int n = 0, r;
3535
3536 /* Try to umount everything recursively below a
3537 * directory. Also, take care of stacked mounts, and keep
3538 * unmounting them until they are gone. */
3539
3540 do {
3541 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
3542
3543 again = false;
3544 r = 0;
3545
3546 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
3547 if (!proc_self_mountinfo)
3548 return -errno;
3549
3550 for (;;) {
3551 _cleanup_free_ char *path = NULL, *p = NULL;
3552 int k;
3553
3554 k = fscanf(proc_self_mountinfo,
3555 "%*s " /* (1) mount id */
3556 "%*s " /* (2) parent id */
3557 "%*s " /* (3) major:minor */
3558 "%*s " /* (4) root */
3559 "%ms " /* (5) mount point */
3560 "%*s" /* (6) mount options */
3561 "%*[^-]" /* (7) optional fields */
3562 "- " /* (8) separator */
3563 "%*s " /* (9) file system type */
3564 "%*s" /* (10) mount source */
3565 "%*s" /* (11) mount options 2 */
3566 "%*[^\n]", /* some rubbish at the end */
3567 &path);
3568 if (k != 1) {
3569 if (k == EOF)
3570 break;
3571
3572 continue;
3573 }
3574
3575 r = cunescape(path, UNESCAPE_RELAX, &p);
3576 if (r < 0)
3577 return r;
3578
3579 if (!path_startswith(p, prefix))
3580 continue;
3581
3582 if (umount2(p, flags) < 0) {
3583 r = -errno;
3584 continue;
3585 }
3586
3587 again = true;
3588 n++;
3589
3590 break;
3591 }
3592
3593 } while (again);
3594
3595 return r ? r : n;
3596 }
3597
3598 static int get_mount_flags(const char *path, unsigned long *flags) {
3599 struct statvfs buf;
3600
3601 if (statvfs(path, &buf) < 0)
3602 return -errno;
3603 *flags = buf.f_flag;
3604 return 0;
3605 }
3606
3607 int bind_remount_recursive(const char *prefix, bool ro) {
3608 _cleanup_set_free_free_ Set *done = NULL;
3609 _cleanup_free_ char *cleaned = NULL;
3610 int r;
3611
3612 /* Recursively remount a directory (and all its submounts)
3613 * read-only or read-write. If the directory is already
3614 * mounted, we reuse the mount and simply mark it
3615 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
3616 * operation). If it isn't we first make it one. Afterwards we
3617 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
3618 * submounts we can access, too. When mounts are stacked on
3619 * the same mount point we only care for each individual
3620 * "top-level" mount on each point, as we cannot
3621 * influence/access the underlying mounts anyway. We do not
3622 * have any effect on future submounts that might get
3623 * propagated, they migt be writable. This includes future
3624 * submounts that have been triggered via autofs. */
3625
3626 cleaned = strdup(prefix);
3627 if (!cleaned)
3628 return -ENOMEM;
3629
3630 path_kill_slashes(cleaned);
3631
3632 done = set_new(&string_hash_ops);
3633 if (!done)
3634 return -ENOMEM;
3635
3636 for (;;) {
3637 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
3638 _cleanup_set_free_free_ Set *todo = NULL;
3639 bool top_autofs = false;
3640 char *x;
3641 unsigned long orig_flags;
3642
3643 todo = set_new(&string_hash_ops);
3644 if (!todo)
3645 return -ENOMEM;
3646
3647 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
3648 if (!proc_self_mountinfo)
3649 return -errno;
3650
3651 for (;;) {
3652 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
3653 int k;
3654
3655 k = fscanf(proc_self_mountinfo,
3656 "%*s " /* (1) mount id */
3657 "%*s " /* (2) parent id */
3658 "%*s " /* (3) major:minor */
3659 "%*s " /* (4) root */
3660 "%ms " /* (5) mount point */
3661 "%*s" /* (6) mount options (superblock) */
3662 "%*[^-]" /* (7) optional fields */
3663 "- " /* (8) separator */
3664 "%ms " /* (9) file system type */
3665 "%*s" /* (10) mount source */
3666 "%*s" /* (11) mount options (bind mount) */
3667 "%*[^\n]", /* some rubbish at the end */
3668 &path,
3669 &type);
3670 if (k != 2) {
3671 if (k == EOF)
3672 break;
3673
3674 continue;
3675 }
3676
3677 r = cunescape(path, UNESCAPE_RELAX, &p);
3678 if (r < 0)
3679 return r;
3680
3681 /* Let's ignore autofs mounts. If they aren't
3682 * triggered yet, we want to avoid triggering
3683 * them, as we don't make any guarantees for
3684 * future submounts anyway. If they are
3685 * already triggered, then we will find
3686 * another entry for this. */
3687 if (streq(type, "autofs")) {
3688 top_autofs = top_autofs || path_equal(cleaned, p);
3689 continue;
3690 }
3691
3692 if (path_startswith(p, cleaned) &&
3693 !set_contains(done, p)) {
3694
3695 r = set_consume(todo, p);
3696 p = NULL;
3697
3698 if (r == -EEXIST)
3699 continue;
3700 if (r < 0)
3701 return r;
3702 }
3703 }
3704
3705 /* If we have no submounts to process anymore and if
3706 * the root is either already done, or an autofs, we
3707 * are done */
3708 if (set_isempty(todo) &&
3709 (top_autofs || set_contains(done, cleaned)))
3710 return 0;
3711
3712 if (!set_contains(done, cleaned) &&
3713 !set_contains(todo, cleaned)) {
3714 /* The prefix directory itself is not yet a
3715 * mount, make it one. */
3716 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
3717 return -errno;
3718
3719 orig_flags = 0;
3720 (void) get_mount_flags(cleaned, &orig_flags);
3721 orig_flags &= ~MS_RDONLY;
3722
3723 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
3724 return -errno;
3725
3726 x = strdup(cleaned);
3727 if (!x)
3728 return -ENOMEM;
3729
3730 r = set_consume(done, x);
3731 if (r < 0)
3732 return r;
3733 }
3734
3735 while ((x = set_steal_first(todo))) {
3736
3737 r = set_consume(done, x);
3738 if (r == -EEXIST || r == 0)
3739 continue;
3740 if (r < 0)
3741 return r;
3742
3743 /* Try to reuse the original flag set, but
3744 * don't care for errors, in case of
3745 * obstructed mounts */
3746 orig_flags = 0;
3747 (void) get_mount_flags(x, &orig_flags);
3748 orig_flags &= ~MS_RDONLY;
3749
3750 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
3751
3752 /* Deal with mount points that are
3753 * obstructed by a later mount */
3754
3755 if (errno != ENOENT)
3756 return -errno;
3757 }
3758
3759 }
3760 }
3761 }
3762
3763 int fflush_and_check(FILE *f) {
3764 assert(f);
3765
3766 errno = 0;
3767 fflush(f);
3768
3769 if (ferror(f))
3770 return errno ? -errno : -EIO;
3771
3772 return 0;
3773 }
3774
3775 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
3776 const char *fn;
3777 char *t;
3778
3779 assert(p);
3780 assert(ret);
3781
3782 /*
3783 * Turns this:
3784 * /foo/bar/waldo
3785 *
3786 * Into this:
3787 * /foo/bar/.#<extra>waldoXXXXXX
3788 */
3789
3790 fn = basename(p);
3791 if (!filename_is_valid(fn))
3792 return -EINVAL;
3793
3794 if (extra == NULL)
3795 extra = "";
3796
3797 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
3798 if (!t)
3799 return -ENOMEM;
3800
3801 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
3802
3803 *ret = path_kill_slashes(t);
3804 return 0;
3805 }
3806
3807 int tempfn_random(const char *p, const char *extra, char **ret) {
3808 const char *fn;
3809 char *t, *x;
3810 uint64_t u;
3811 unsigned i;
3812
3813 assert(p);
3814 assert(ret);
3815
3816 /*
3817 * Turns this:
3818 * /foo/bar/waldo
3819 *
3820 * Into this:
3821 * /foo/bar/.#<extra>waldobaa2a261115984a9
3822 */
3823
3824 fn = basename(p);
3825 if (!filename_is_valid(fn))
3826 return -EINVAL;
3827
3828 if (!extra)
3829 extra = "";
3830
3831 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
3832 if (!t)
3833 return -ENOMEM;
3834
3835 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
3836
3837 u = random_u64();
3838 for (i = 0; i < 16; i++) {
3839 *(x++) = hexchar(u & 0xF);
3840 u >>= 4;
3841 }
3842
3843 *x = 0;
3844
3845 *ret = path_kill_slashes(t);
3846 return 0;
3847 }
3848
3849 int tempfn_random_child(const char *p, const char *extra, char **ret) {
3850 char *t, *x;
3851 uint64_t u;
3852 unsigned i;
3853
3854 assert(p);
3855 assert(ret);
3856
3857 /* Turns this:
3858 * /foo/bar/waldo
3859 * Into this:
3860 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
3861 */
3862
3863 if (!extra)
3864 extra = "";
3865
3866 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
3867 if (!t)
3868 return -ENOMEM;
3869
3870 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
3871
3872 u = random_u64();
3873 for (i = 0; i < 16; i++) {
3874 *(x++) = hexchar(u & 0xF);
3875 u >>= 4;
3876 }
3877
3878 *x = 0;
3879
3880 *ret = path_kill_slashes(t);
3881 return 0;
3882 }
3883
3884 int take_password_lock(const char *root) {
3885
3886 struct flock flock = {
3887 .l_type = F_WRLCK,
3888 .l_whence = SEEK_SET,
3889 .l_start = 0,
3890 .l_len = 0,
3891 };
3892
3893 const char *path;
3894 int fd, r;
3895
3896 /* This is roughly the same as lckpwdf(), but not as awful. We
3897 * don't want to use alarm() and signals, hence we implement
3898 * our own trivial version of this.
3899 *
3900 * Note that shadow-utils also takes per-database locks in
3901 * addition to lckpwdf(). However, we don't given that they
3902 * are redundant as they they invoke lckpwdf() first and keep
3903 * it during everything they do. The per-database locks are
3904 * awfully racy, and thus we just won't do them. */
3905
3906 if (root)
3907 path = strjoina(root, "/etc/.pwd.lock");
3908 else
3909 path = "/etc/.pwd.lock";
3910
3911 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
3912 if (fd < 0)
3913 return -errno;
3914
3915 r = fcntl(fd, F_SETLKW, &flock);
3916 if (r < 0) {
3917 safe_close(fd);
3918 return -errno;
3919 }
3920
3921 return fd;
3922 }
3923
3924 int is_symlink(const char *path) {
3925 struct stat info;
3926
3927 if (lstat(path, &info) < 0)
3928 return -errno;
3929
3930 return !!S_ISLNK(info.st_mode);
3931 }
3932
3933 int is_dir(const char* path, bool follow) {
3934 struct stat st;
3935 int r;
3936
3937 if (follow)
3938 r = stat(path, &st);
3939 else
3940 r = lstat(path, &st);
3941 if (r < 0)
3942 return -errno;
3943
3944 return !!S_ISDIR(st.st_mode);
3945 }
3946
3947 int is_device_node(const char *path) {
3948 struct stat info;
3949
3950 if (lstat(path, &info) < 0)
3951 return -errno;
3952
3953 return !!(S_ISBLK(info.st_mode) || S_ISCHR(info.st_mode));
3954 }
3955
3956 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
3957 char fn[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
3958 _cleanup_close_ int fd = -1;
3959 ssize_t l;
3960
3961 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
3962
3963 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_PATH|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
3964 if (fd < 0)
3965 return -errno;
3966
3967 xsprintf(fn, "/proc/self/fd/%i", fd);
3968
3969 l = getxattr(fn, attribute, value, size);
3970 if (l < 0)
3971 return -errno;
3972
3973 return l;
3974 }
3975
3976 static int parse_crtime(le64_t le, usec_t *usec) {
3977 uint64_t u;
3978
3979 assert(usec);
3980
3981 u = le64toh(le);
3982 if (u == 0 || u == (uint64_t) -1)
3983 return -EIO;
3984
3985 *usec = (usec_t) u;
3986 return 0;
3987 }
3988
3989 int fd_getcrtime(int fd, usec_t *usec) {
3990 le64_t le;
3991 ssize_t n;
3992
3993 assert(fd >= 0);
3994 assert(usec);
3995
3996 /* Until Linux gets a real concept of birthtime/creation time,
3997 * let's fake one with xattrs */
3998
3999 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
4000 if (n < 0)
4001 return -errno;
4002 if (n != sizeof(le))
4003 return -EIO;
4004
4005 return parse_crtime(le, usec);
4006 }
4007
4008 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
4009 le64_t le;
4010 ssize_t n;
4011
4012 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
4013 if (n < 0)
4014 return -errno;
4015 if (n != sizeof(le))
4016 return -EIO;
4017
4018 return parse_crtime(le, usec);
4019 }
4020
4021 int path_getcrtime(const char *p, usec_t *usec) {
4022 le64_t le;
4023 ssize_t n;
4024
4025 assert(p);
4026 assert(usec);
4027
4028 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
4029 if (n < 0)
4030 return -errno;
4031 if (n != sizeof(le))
4032 return -EIO;
4033
4034 return parse_crtime(le, usec);
4035 }
4036
4037 int fd_setcrtime(int fd, usec_t usec) {
4038 le64_t le;
4039
4040 assert(fd >= 0);
4041
4042 if (usec <= 0)
4043 usec = now(CLOCK_REALTIME);
4044
4045 le = htole64((uint64_t) usec);
4046 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
4047 return -errno;
4048
4049 return 0;
4050 }
4051
4052 int chattr_fd(int fd, unsigned value, unsigned mask) {
4053 unsigned old_attr, new_attr;
4054 struct stat st;
4055
4056 assert(fd >= 0);
4057
4058 if (fstat(fd, &st) < 0)
4059 return -errno;
4060
4061 /* Explicitly check whether this is a regular file or
4062 * directory. If it is anything else (such as a device node or
4063 * fifo), then the ioctl will not hit the file systems but
4064 * possibly drivers, where the ioctl might have different
4065 * effects. Notably, DRM is using the same ioctl() number. */
4066
4067 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
4068 return -ENOTTY;
4069
4070 if (mask == 0)
4071 return 0;
4072
4073 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
4074 return -errno;
4075
4076 new_attr = (old_attr & ~mask) | (value & mask);
4077 if (new_attr == old_attr)
4078 return 0;
4079
4080 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
4081 return -errno;
4082
4083 return 1;
4084 }
4085
4086 int chattr_path(const char *p, unsigned value, unsigned mask) {
4087 _cleanup_close_ int fd = -1;
4088
4089 assert(p);
4090
4091 if (mask == 0)
4092 return 0;
4093
4094 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
4095 if (fd < 0)
4096 return -errno;
4097
4098 return chattr_fd(fd, value, mask);
4099 }
4100
4101 int read_attr_fd(int fd, unsigned *ret) {
4102 struct stat st;
4103
4104 assert(fd >= 0);
4105
4106 if (fstat(fd, &st) < 0)
4107 return -errno;
4108
4109 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
4110 return -ENOTTY;
4111
4112 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
4113 return -errno;
4114
4115 return 0;
4116 }
4117
4118 int read_attr_path(const char *p, unsigned *ret) {
4119 _cleanup_close_ int fd = -1;
4120
4121 assert(p);
4122 assert(ret);
4123
4124 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
4125 if (fd < 0)
4126 return -errno;
4127
4128 return read_attr_fd(fd, ret);
4129 }
4130
4131 void sigkill_wait(pid_t *pid) {
4132 if (!pid)
4133 return;
4134 if (*pid <= 1)
4135 return;
4136
4137 if (kill(*pid, SIGKILL) > 0)
4138 (void) wait_for_terminate(*pid, NULL);
4139 }
4140
4141 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
4142 int a = 0, b = 0, c = 0;
4143 int k;
4144
4145 assert(p);
4146 assert(*p);
4147 assert(priority);
4148
4149 if ((*p)[0] != '<')
4150 return 0;
4151
4152 if (!strchr(*p, '>'))
4153 return 0;
4154
4155 if ((*p)[2] == '>') {
4156 c = undecchar((*p)[1]);
4157 k = 3;
4158 } else if ((*p)[3] == '>') {
4159 b = undecchar((*p)[1]);
4160 c = undecchar((*p)[2]);
4161 k = 4;
4162 } else if ((*p)[4] == '>') {
4163 a = undecchar((*p)[1]);
4164 b = undecchar((*p)[2]);
4165 c = undecchar((*p)[3]);
4166 k = 5;
4167 } else
4168 return 0;
4169
4170 if (a < 0 || b < 0 || c < 0 ||
4171 (!with_facility && (a || b || c > 7)))
4172 return 0;
4173
4174 if (with_facility)
4175 *priority = a*100 + b*10 + c;
4176 else
4177 *priority = (*priority & LOG_FACMASK) | c;
4178
4179 *p += k;
4180 return 1;
4181 }
4182
4183 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
4184 size_t i;
4185
4186 if (!key)
4187 return -1;
4188
4189 for (i = 0; i < len; ++i)
4190 if (streq_ptr(table[i], key))
4191 return (ssize_t) i;
4192
4193 return -1;
4194 }
4195
4196 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
4197 struct stat buf;
4198 int ret;
4199
4200 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
4201 if (ret >= 0)
4202 return 0;
4203
4204 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
4205 * If it is not implemented, fallback to another method. */
4206 if (!IN_SET(errno, EINVAL, ENOSYS))
4207 return -errno;
4208
4209 /* The link()/unlink() fallback does not work on directories. But
4210 * renameat() without RENAME_NOREPLACE gives the same semantics on
4211 * directories, except when newpath is an *empty* directory. This is
4212 * good enough. */
4213 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
4214 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
4215 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
4216 return ret >= 0 ? 0 : -errno;
4217 }
4218
4219 /* If it is not a directory, use the link()/unlink() fallback. */
4220 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
4221 if (ret < 0)
4222 return -errno;
4223
4224 ret = unlinkat(olddirfd, oldpath, 0);
4225 if (ret < 0) {
4226 /* backup errno before the following unlinkat() alters it */
4227 ret = errno;
4228 (void) unlinkat(newdirfd, newpath, 0);
4229 errno = ret;
4230 return -errno;
4231 }
4232
4233 return 0;
4234 }
4235
4236 int parse_mode(const char *s, mode_t *ret) {
4237 char *x;
4238 long l;
4239
4240 assert(s);
4241 assert(ret);
4242
4243 errno = 0;
4244 l = strtol(s, &x, 8);
4245 if (errno != 0)
4246 return -errno;
4247
4248 if (!x || x == s || *x)
4249 return -EINVAL;
4250 if (l < 0 || l > 07777)
4251 return -ERANGE;
4252
4253 *ret = (mode_t) l;
4254 return 0;
4255 }
4256
4257 int mount_move_root(const char *path) {
4258 assert(path);
4259
4260 if (chdir(path) < 0)
4261 return -errno;
4262
4263 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
4264 return -errno;
4265
4266 if (chroot(".") < 0)
4267 return -errno;
4268
4269 if (chdir("/") < 0)
4270 return -errno;
4271
4272 return 0;
4273 }
4274
4275 int getxattr_malloc(const char *path, const char *name, char **value, bool allow_symlink) {
4276 char *v;
4277 size_t l;
4278 ssize_t n;
4279
4280 assert(path);
4281 assert(name);
4282 assert(value);
4283
4284 for (l = 100; ; l = (size_t) n + 1) {
4285 v = new0(char, l);
4286 if (!v)
4287 return -ENOMEM;
4288
4289 if (allow_symlink)
4290 n = lgetxattr(path, name, v, l);
4291 else
4292 n = getxattr(path, name, v, l);
4293
4294 if (n >= 0 && (size_t) n < l) {
4295 *value = v;
4296 return n;
4297 }
4298
4299 free(v);
4300
4301 if (n < 0 && errno != ERANGE)
4302 return -errno;
4303
4304 if (allow_symlink)
4305 n = lgetxattr(path, name, NULL, 0);
4306 else
4307 n = getxattr(path, name, NULL, 0);
4308 if (n < 0)
4309 return -errno;
4310 }
4311 }
4312
4313 int fgetxattr_malloc(int fd, const char *name, char **value) {
4314 char *v;
4315 size_t l;
4316 ssize_t n;
4317
4318 assert(fd >= 0);
4319 assert(name);
4320 assert(value);
4321
4322 for (l = 100; ; l = (size_t) n + 1) {
4323 v = new0(char, l);
4324 if (!v)
4325 return -ENOMEM;
4326
4327 n = fgetxattr(fd, name, v, l);
4328
4329 if (n >= 0 && (size_t) n < l) {
4330 *value = v;
4331 return n;
4332 }
4333
4334 free(v);
4335
4336 if (n < 0 && errno != ERANGE)
4337 return -errno;
4338
4339 n = fgetxattr(fd, name, NULL, 0);
4340 if (n < 0)
4341 return -errno;
4342 }
4343 }
4344
4345 int send_one_fd(int transport_fd, int fd, int flags) {
4346 union {
4347 struct cmsghdr cmsghdr;
4348 uint8_t buf[CMSG_SPACE(sizeof(int))];
4349 } control = {};
4350 struct msghdr mh = {
4351 .msg_control = &control,
4352 .msg_controllen = sizeof(control),
4353 };
4354 struct cmsghdr *cmsg;
4355
4356 assert(transport_fd >= 0);
4357 assert(fd >= 0);
4358
4359 cmsg = CMSG_FIRSTHDR(&mh);
4360 cmsg->cmsg_level = SOL_SOCKET;
4361 cmsg->cmsg_type = SCM_RIGHTS;
4362 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
4363 memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
4364
4365 mh.msg_controllen = CMSG_SPACE(sizeof(int));
4366 if (sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags) < 0)
4367 return -errno;
4368
4369 return 0;
4370 }
4371
4372 int receive_one_fd(int transport_fd, int flags) {
4373 union {
4374 struct cmsghdr cmsghdr;
4375 uint8_t buf[CMSG_SPACE(sizeof(int))];
4376 } control = {};
4377 struct msghdr mh = {
4378 .msg_control = &control,
4379 .msg_controllen = sizeof(control),
4380 };
4381 struct cmsghdr *cmsg, *found = NULL;
4382
4383 assert(transport_fd >= 0);
4384
4385 /*
4386 * Receive a single FD via @transport_fd. We don't care for
4387 * the transport-type. We retrieve a single FD at most, so for
4388 * packet-based transports, the caller must ensure to send
4389 * only a single FD per packet. This is best used in
4390 * combination with send_one_fd().
4391 */
4392
4393 if (recvmsg(transport_fd, &mh, MSG_NOSIGNAL | MSG_CMSG_CLOEXEC | flags) < 0)
4394 return -errno;
4395
4396 CMSG_FOREACH(cmsg, &mh) {
4397 if (cmsg->cmsg_level == SOL_SOCKET &&
4398 cmsg->cmsg_type == SCM_RIGHTS &&
4399 cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
4400 assert(!found);
4401 found = cmsg;
4402 break;
4403 }
4404 }
4405
4406 if (!found) {
4407 cmsg_close_all(&mh);
4408 return -EIO;
4409 }
4410
4411 return *(int*) CMSG_DATA(found);
4412 }
4413
4414 void nop_signal_handler(int sig) {
4415 /* nothing here */
4416 }
4417
4418 int version(void) {
4419 puts(PACKAGE_STRING "\n"
4420 SYSTEMD_FEATURES);
4421 return 0;
4422 }
4423
4424 bool fdname_is_valid(const char *s) {
4425 const char *p;
4426
4427 /* Validates a name for $LISTEN_FDNAMES. We basically allow
4428 * everything ASCII that's not a control character. Also, as
4429 * special exception the ":" character is not allowed, as we
4430 * use that as field separator in $LISTEN_FDNAMES.
4431 *
4432 * Note that the empty string is explicitly allowed
4433 * here. However, we limit the length of the names to 255
4434 * characters. */
4435
4436 if (!s)
4437 return false;
4438
4439 for (p = s; *p; p++) {
4440 if (*p < ' ')
4441 return false;
4442 if (*p >= 127)
4443 return false;
4444 if (*p == ':')
4445 return false;
4446 }
4447
4448 return p - s < 256;
4449 }
4450
4451 bool oom_score_adjust_is_valid(int oa) {
4452 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
4453 }