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