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