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