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