]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/util.c
networkd: fix use-after-free
[thirdparty/systemd.git] / src / shared / util.c
CommitLineData
d6c9574f 1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
60918275 2
a7334b09
LP
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
5430f7f2
LP
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
a7334b09
LP
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
5430f7f2 16 Lesser General Public License for more details.
a7334b09 17
5430f7f2 18 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20***/
21
60918275
LP
22#include <assert.h>
23#include <string.h>
24#include <unistd.h>
25#include <errno.h>
85261803 26#include <stdlib.h>
034c6ed7
LP
27#include <signal.h>
28#include <stdio.h>
1dccbe19
LP
29#include <syslog.h>
30#include <sched.h>
31#include <sys/resource.h>
ef886c6a 32#include <linux/sched.h>
a9f5d454
LP
33#include <sys/types.h>
34#include <sys/stat.h>
3a0ecb08 35#include <fcntl.h>
a0d40ac5 36#include <dirent.h>
601f6a1e
LP
37#include <sys/ioctl.h>
38#include <linux/vt.h>
39#include <linux/tiocl.h>
80876c20
LP
40#include <termios.h>
41#include <stdarg.h>
42#include <sys/inotify.h>
43#include <sys/poll.h>
3177a7fa 44#include <ctype.h>
5b6319dc 45#include <sys/prctl.h>
ef2f1067
LP
46#include <sys/utsname.h>
47#include <pwd.h>
4fd5948e 48#include <netinet/ip.h>
3fe5e5d4 49#include <linux/kd.h>
afea26ad 50#include <dlfcn.h>
2e78aa99 51#include <sys/wait.h>
7948c4df 52#include <sys/time.h>
8092a428 53#include <glob.h>
4b67834e 54#include <grp.h>
87d2c1ff 55#include <sys/mman.h>
825c6fe5 56#include <sys/vfs.h>
6d313367 57#include <sys/mount.h>
825c6fe5 58#include <linux/magic.h>
0b507b17 59#include <limits.h>
09017585
MS
60#include <langinfo.h>
61#include <locale.h>
6afc95b7 62#include <sys/personality.h>
844ec79b 63#include <libgen.h>
2b6bf07d 64#undef basename
60918275 65
9bf3b535
LP
66#ifdef HAVE_SYS_AUXV_H
67#include <sys/auxv.h>
68#endif
69
60918275
LP
70#include "macro.h"
71#include "util.h"
1dccbe19
LP
72#include "ioprio.h"
73#include "missing.h"
a9f5d454 74#include "log.h"
65d2ebdc 75#include "strv.h"
e51bc1a2 76#include "label.h"
c38dfac9 77#include "mkdir.h"
9eb977db 78#include "path-util.h"
d06dacd0 79#include "exit-status.h"
83cc030f 80#include "hashmap.h"
4d1a6904 81#include "env-util.h"
a5c32cff 82#include "fileio.h"
8f6ce71f 83#include "device-nodes.h"
f405e86d
SL
84#include "utf8.h"
85#include "gunicode.h"
295edddf 86#include "virt.h"
477def80 87#include "def.h"
56cf987f 88
9a0e6896
LP
89int saved_argc = 0;
90char **saved_argv = NULL;
9086e840 91
28917d7d 92static volatile unsigned cached_columns = 0;
ed757c0c 93static volatile unsigned cached_lines = 0;
9a0e6896 94
37f85e66 95size_t page_size(void) {
ec202eae 96 static thread_local size_t pgsz = 0;
37f85e66 97 long r;
98
87d2c1ff 99 if (_likely_(pgsz > 0))
37f85e66 100 return pgsz;
101
e67f47e5
LP
102 r = sysconf(_SC_PAGESIZE);
103 assert(r > 0);
37f85e66 104
105 pgsz = (size_t) r;
37f85e66 106 return pgsz;
107}
108
e05797fb
LP
109bool streq_ptr(const char *a, const char *b) {
110
111 /* Like streq(), but tries to make sense of NULL pointers */
112
113 if (a && b)
114 return streq(a, b);
115
116 if (!a && !b)
117 return true;
118
119 return false;
120}
121
8c7c140f 122char* endswith(const char *s, const char *postfix) {
60918275
LP
123 size_t sl, pl;
124
125 assert(s);
126 assert(postfix);
127
128 sl = strlen(s);
129 pl = strlen(postfix);
130
d4d0d4db 131 if (pl == 0)
8c7c140f 132 return (char*) s + sl;
d4d0d4db 133
60918275 134 if (sl < pl)
8c7c140f
LP
135 return NULL;
136
137 if (memcmp(s + sl - pl, postfix, pl) != 0)
138 return NULL;
60918275 139
8c7c140f 140 return (char*) s + sl - pl;
60918275
LP
141}
142
5cb36f41 143char* first_word(const char *s, const char *word) {
79d6d816 144 size_t sl, wl;
5cb36f41 145 const char *p;
79d6d816
LP
146
147 assert(s);
148 assert(word);
149
5cb36f41
LP
150 /* Checks if the string starts with the specified word, either
151 * followed by NUL or by whitespace. Returns a pointer to the
152 * NUL or the first character after the whitespace. */
153
79d6d816
LP
154 sl = strlen(s);
155 wl = strlen(word);
156
157 if (sl < wl)
5cb36f41 158 return NULL;
79d6d816 159
d4d0d4db 160 if (wl == 0)
5cb36f41 161 return (char*) s;
d4d0d4db 162
79d6d816 163 if (memcmp(s, word, wl) != 0)
5cb36f41
LP
164 return NULL;
165
166 p = s + wl;
167 if (*p == 0)
168 return (char*) p;
169
170 if (!strchr(WHITESPACE, *p))
171 return NULL;
79d6d816 172
5cb36f41
LP
173 p += strspn(p, WHITESPACE);
174 return (char*) p;
79d6d816
LP
175}
176
42f4e3c4 177int close_nointr(int fd) {
b0ee8068 178 int r;
60918275 179
b0ee8068
CW
180 assert(fd >= 0);
181 r = close(fd);
d96ea504 182 if (r >= 0)
b0ee8068 183 return r;
d96ea504
LP
184 else if (errno == EINTR)
185 /*
186 * Just ignore EINTR; a retry loop is the wrong
187 * thing to do on Linux.
188 *
189 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
190 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
191 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
192 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
193 */
194 return 0;
b0ee8068
CW
195 else
196 return -errno;
60918275 197}
85261803 198
03e334a1
LP
199int safe_close(int fd) {
200
201 /*
202 * Like close_nointr() but cannot fail. Guarantees errno is
203 * unchanged. Is a NOP with negative fds passed, and returns
204 * -1, so that it can be used in this syntax:
205 *
206 * fd = safe_close(fd);
207 */
85f136b5 208
03e334a1
LP
209 if (fd >= 0) {
210 PROTECT_ERRNO;
d96ea504
LP
211
212 /* The kernel might return pretty much any error code
213 * via close(), but the fd will be closed anyway. The
214 * only condition we want to check for here is whether
215 * the fd was invalid at all... */
216
217 assert_se(close_nointr(fd) != -EBADF);
03e334a1 218 }
85f136b5 219
03e334a1 220 return -1;
85f136b5
LP
221}
222
5b6319dc
LP
223void close_many(const int fds[], unsigned n_fd) {
224 unsigned i;
225
2c93b4ef
LP
226 assert(fds || n_fd <= 0);
227
5b6319dc 228 for (i = 0; i < n_fd; i++)
03e334a1 229 safe_close(fds[i]);
5b6319dc
LP
230}
231
4b73a0c0
LP
232int unlink_noerrno(const char *path) {
233 PROTECT_ERRNO;
234 int r;
235
236 r = unlink(path);
237 if (r < 0)
238 return -errno;
239
240 return 0;
241}
242
85261803
LP
243int parse_boolean(const char *v) {
244 assert(v);
245
0f625d0b 246 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
85261803 247 return 1;
0f625d0b 248 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
85261803
LP
249 return 0;
250
251 return -EINVAL;
252}
253
3ba686c1 254int parse_pid(const char *s, pid_t* ret_pid) {
0b172489 255 unsigned long ul = 0;
3ba686c1
LP
256 pid_t pid;
257 int r;
258
259 assert(s);
260 assert(ret_pid);
261
e67f47e5
LP
262 r = safe_atolu(s, &ul);
263 if (r < 0)
3ba686c1
LP
264 return r;
265
266 pid = (pid_t) ul;
267
268 if ((unsigned long) pid != ul)
269 return -ERANGE;
270
271 if (pid <= 0)
272 return -ERANGE;
273
274 *ret_pid = pid;
275 return 0;
276}
277
034a2a52
LP
278int parse_uid(const char *s, uid_t* ret_uid) {
279 unsigned long ul = 0;
280 uid_t uid;
281 int r;
282
283 assert(s);
284 assert(ret_uid);
285
e67f47e5
LP
286 r = safe_atolu(s, &ul);
287 if (r < 0)
034a2a52
LP
288 return r;
289
290 uid = (uid_t) ul;
291
292 if ((unsigned long) uid != ul)
293 return -ERANGE;
294
306a55c8
LP
295 /* Some libc APIs use (uid_t) -1 as special placeholder */
296 if (uid == (uid_t) 0xFFFFFFFF)
f841a154 297 return -ENXIO;
306a55c8 298
6afeb1cf 299 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
306a55c8 300 if (uid == (uid_t) 0xFFFF)
f841a154 301 return -ENXIO;
306a55c8 302
034a2a52
LP
303 *ret_uid = uid;
304 return 0;
305}
306
85261803
LP
307int safe_atou(const char *s, unsigned *ret_u) {
308 char *x = NULL;
034c6ed7 309 unsigned long l;
85261803
LP
310
311 assert(s);
312 assert(ret_u);
313
314 errno = 0;
315 l = strtoul(s, &x, 0);
316
f3910003 317 if (!x || x == s || *x || errno)
48deb058 318 return errno > 0 ? -errno : -EINVAL;
85261803 319
034c6ed7 320 if ((unsigned long) (unsigned) l != l)
85261803
LP
321 return -ERANGE;
322
323 *ret_u = (unsigned) l;
324 return 0;
325}
326
327int safe_atoi(const char *s, int *ret_i) {
328 char *x = NULL;
034c6ed7 329 long l;
85261803
LP
330
331 assert(s);
332 assert(ret_i);
333
334 errno = 0;
335 l = strtol(s, &x, 0);
336
f3910003 337 if (!x || x == s || *x || errno)
48deb058 338 return errno > 0 ? -errno : -EINVAL;
85261803 339
034c6ed7 340 if ((long) (int) l != l)
85261803
LP
341 return -ERANGE;
342
034c6ed7
LP
343 *ret_i = (int) l;
344 return 0;
345}
346
b914e211
LP
347int safe_atou8(const char *s, uint8_t *ret) {
348 char *x = NULL;
349 unsigned long l;
350
351 assert(s);
352 assert(ret);
353
354 errno = 0;
355 l = strtoul(s, &x, 0);
356
357 if (!x || x == s || *x || errno)
358 return errno > 0 ? -errno : -EINVAL;
359
360 if ((unsigned long) (uint8_t) l != l)
361 return -ERANGE;
362
363 *ret = (uint8_t) l;
364 return 0;
365}
366
034c6ed7
LP
367int safe_atollu(const char *s, long long unsigned *ret_llu) {
368 char *x = NULL;
369 unsigned long long l;
370
371 assert(s);
372 assert(ret_llu);
373
374 errno = 0;
375 l = strtoull(s, &x, 0);
376
f3910003 377 if (!x || x == s || *x || errno)
034c6ed7
LP
378 return errno ? -errno : -EINVAL;
379
380 *ret_llu = l;
381 return 0;
382}
383
384int safe_atolli(const char *s, long long int *ret_lli) {
385 char *x = NULL;
386 long long l;
387
388 assert(s);
389 assert(ret_lli);
390
391 errno = 0;
392 l = strtoll(s, &x, 0);
393
f3910003 394 if (!x || x == s || *x || errno)
034c6ed7
LP
395 return errno ? -errno : -EINVAL;
396
397 *ret_lli = l;
85261803
LP
398 return 0;
399}
a41e8209 400
f7900e25
TA
401int safe_atod(const char *s, double *ret_d) {
402 char *x = NULL;
32b2634e 403 double d = 0;
f7900e25
TA
404
405 assert(s);
406 assert(ret_d);
407
d6dd604b
LP
408 RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
409 errno = 0;
410 d = strtod(s, &x);
411 }
f7900e25
TA
412
413 if (!x || x == s || *x || errno)
414 return errno ? -errno : -EINVAL;
415
416 *ret_d = (double) d;
417 return 0;
418}
419
bf85c24d
SP
420static size_t strcspn_escaped(const char *s, const char *reject) {
421 bool escaped = false;
422 size_t n;
423
424 for (n=0; s[n]; n++) {
425 if (escaped)
426 escaped = false;
427 else if (s[n] == '\\')
428 escaped = true;
429 else if (strchr(reject, s[n]))
a2a5291b 430 break;
bf85c24d 431 }
a2a5291b
ZJS
432 /* if s ends in \, return index of previous char */
433 return n - escaped;
bf85c24d
SP
434}
435
a41e8209 436/* Split a string into words. */
a2a5291b
ZJS
437const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
438 const char *current;
a41e8209 439
a2a5291b 440 current = *state;
a41e8209 441
a2a5291b
ZJS
442 if (!*current) {
443 assert(**state == '\0');
a41e8209 444 return NULL;
a2a5291b 445 }
a41e8209 446
65d2ebdc 447 current += strspn(current, separator);
a2a5291b
ZJS
448 if (!*current) {
449 *state = current;
70f75a52 450 return NULL;
a2a5291b 451 }
70f75a52 452
bf85c24d 453 if (quoted && strchr("\'\"", *current)) {
a2a5291b
ZJS
454 char quotechars[2] = {*current, '\0'};
455
456 *l = strcspn_escaped(current + 1, quotechars);
457 if (current[*l + 1] == '\0' ||
458 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
459 /* right quote missing or garbage at the end*/
460 *state = current;
461 return NULL;
462 }
463 assert(current[*l + 1] == quotechars[0]);
464 *state = current++ + *l + 2;
bf85c24d
SP
465 } else if (quoted) {
466 *l = strcspn_escaped(current, separator);
a2a5291b 467 *state = current + *l;
034c6ed7 468 } else {
bf85c24d 469 *l = strcspn(current, separator);
a2a5291b 470 *state = current + *l;
034c6ed7
LP
471 }
472
a2a5291b 473 return current;
034c6ed7
LP
474}
475
034c6ed7
LP
476int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
477 int r;
b4696bce 478 _cleanup_free_ char *line = NULL;
bb00e604 479 long unsigned ppid;
49aa47c7 480 const char *p;
034c6ed7 481
49aa47c7 482 assert(pid >= 0);
034c6ed7
LP
483 assert(_ppid);
484
49aa47c7
LP
485 if (pid == 0) {
486 *_ppid = getppid();
487 return 0;
488 }
034c6ed7 489
49aa47c7 490 p = procfs_file_alloca(pid, "stat");
b4696bce
SP
491 r = read_one_line_file(p, &line);
492 if (r < 0)
034c6ed7 493 return r;
034c6ed7 494
034c6ed7
LP
495 /* Let's skip the pid and comm fields. The latter is enclosed
496 * in () but does not escape any () in its value, so let's
497 * skip over it manually */
498
2fbe635a
LP
499 p = strrchr(line, ')');
500 if (!p)
034c6ed7
LP
501 return -EIO;
502
503 p++;
504
505 if (sscanf(p, " "
506 "%*c " /* state */
bb00e604 507 "%lu ", /* ppid */
034c6ed7
LP
508 &ppid) != 1)
509 return -EIO;
510
bb00e604 511 if ((long unsigned) (pid_t) ppid != ppid)
034c6ed7
LP
512 return -ERANGE;
513
514 *_ppid = (pid_t) ppid;
515
516 return 0;
517}
518
7640a5de 519int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
b4696bce
SP
520 int r;
521 _cleanup_free_ char *line = NULL;
49aa47c7 522 const char *p;
7640a5de 523
49aa47c7 524 assert(pid >= 0);
7640a5de
LP
525 assert(st);
526
b68fa010 527 p = procfs_file_alloca(pid, "stat");
b4696bce
SP
528 r = read_one_line_file(p, &line);
529 if (r < 0)
530 return r;
7640a5de
LP
531
532 /* Let's skip the pid and comm fields. The latter is enclosed
533 * in () but does not escape any () in its value, so let's
534 * skip over it manually */
535
e67f47e5
LP
536 p = strrchr(line, ')');
537 if (!p)
7640a5de
LP
538 return -EIO;
539
540 p++;
541
542 if (sscanf(p, " "
543 "%*c " /* state */
544 "%*d " /* ppid */
545 "%*d " /* pgrp */
546 "%*d " /* session */
547 "%*d " /* tty_nr */
548 "%*d " /* tpgid */
549 "%*u " /* flags */
550 "%*u " /* minflt */
551 "%*u " /* cminflt */
552 "%*u " /* majflt */
553 "%*u " /* cmajflt */
554 "%*u " /* utime */
555 "%*u " /* stime */
556 "%*d " /* cutime */
557 "%*d " /* cstime */
558 "%*d " /* priority */
559 "%*d " /* nice */
560 "%*d " /* num_threads */
561 "%*d " /* itrealvalue */
562 "%llu " /* starttime */,
563 st) != 1)
564 return -EIO;
565
566 return 0;
567}
568
34ca941c
LP
569int fchmod_umask(int fd, mode_t m) {
570 mode_t u;
571 int r;
572
573 u = umask(0777);
574 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
575 umask(u);
576
577 return r;
578}
579
7072ced8
LP
580char *truncate_nl(char *s) {
581 assert(s);
582
583 s[strcspn(s, NEWLINE)] = 0;
584 return s;
585}
586
93b5eaec 587int get_process_state(pid_t pid) {
e10c9985
YS
588 const char *p;
589 char state;
590 int r;
591 _cleanup_free_ char *line = NULL;
592
593 assert(pid >= 0);
594
595 p = procfs_file_alloca(pid, "stat");
596 r = read_one_line_file(p, &line);
597 if (r < 0)
598 return r;
599
600 p = strrchr(line, ')');
601 if (!p)
602 return -EIO;
603
604 p++;
605
606 if (sscanf(p, " %c", &state) != 1)
607 return -EIO;
608
609 return (unsigned char) state;
610}
611
87d2c1ff 612int get_process_comm(pid_t pid, char **name) {
49aa47c7 613 const char *p;
5b12334d 614 int r;
7072ced8 615
7072ced8 616 assert(name);
49aa47c7 617 assert(pid >= 0);
7072ced8 618
b68fa010 619 p = procfs_file_alloca(pid, "comm");
7072ced8 620
5b12334d
LP
621 r = read_one_line_file(p, name);
622 if (r == -ENOENT)
623 return -ESRCH;
624
625 return r;
7072ced8
LP
626}
627
87d2c1ff 628int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
49aa47c7 629 _cleanup_fclose_ FILE *f = NULL;
9bdbc2e2 630 char *r = NULL, *k;
49aa47c7 631 const char *p;
c59760ee 632 int c;
c59760ee 633
c59760ee 634 assert(line);
49aa47c7 635 assert(pid >= 0);
c59760ee 636
b68fa010 637 p = procfs_file_alloca(pid, "cmdline");
c59760ee 638
49aa47c7 639 f = fopen(p, "re");
c59760ee
LP
640 if (!f)
641 return -errno;
49aa47c7 642
9bdbc2e2 643 if (max_length == 0) {
49aa47c7
LP
644 size_t len = 0, allocated = 0;
645
9bdbc2e2 646 while ((c = getc(f)) != EOF) {
49aa47c7
LP
647
648 if (!GREEDY_REALLOC(r, allocated, len+2)) {
9bdbc2e2 649 free(r);
9bdbc2e2
LN
650 return -ENOMEM;
651 }
49aa47c7
LP
652
653 r[len++] = isprint(c) ? c : ' ';
9bdbc2e2 654 }
49aa47c7
LP
655
656 if (len > 0)
657 r[len-1] = 0;
658
9bdbc2e2
LN
659 } else {
660 bool space = false;
661 size_t left;
49aa47c7 662
9bdbc2e2 663 r = new(char, max_length);
49aa47c7 664 if (!r)
9bdbc2e2 665 return -ENOMEM;
c59760ee 666
9bdbc2e2
LN
667 k = r;
668 left = max_length;
669 while ((c = getc(f)) != EOF) {
c59760ee 670
9bdbc2e2
LN
671 if (isprint(c)) {
672 if (space) {
673 if (left <= 4)
674 break;
675
676 *(k++) = ' ';
677 left--;
678 space = false;
679 }
c59760ee 680
c59760ee
LP
681 if (left <= 4)
682 break;
683
9bdbc2e2 684 *(k++) = (char) c;
057fbb58 685 left--;
9bdbc2e2
LN
686 } else
687 space = true;
688 }
c59760ee 689
9bdbc2e2
LN
690 if (left <= 4) {
691 size_t n = MIN(left-1, 3U);
692 memcpy(k, "...", n);
693 k[n] = 0;
694 } else
695 *k = 0;
c59760ee
LP
696 }
697
35d2e7ec 698 /* Kernel threads have no argv[] */
9bdbc2e2 699 if (r == NULL || r[0] == 0) {
b47d419c 700 _cleanup_free_ char *t = NULL;
35d2e7ec
LP
701 int h;
702
703 free(r);
704
87d2c1ff
LP
705 if (!comm_fallback)
706 return -ENOENT;
707
708 h = get_process_comm(pid, &t);
709 if (h < 0)
35d2e7ec
LP
710 return h;
711
b7def684 712 r = strjoin("[", t, "]", NULL);
87d2c1ff 713 if (!r)
35d2e7ec
LP
714 return -ENOMEM;
715 }
fa776d8e 716
c59760ee
LP
717 *line = r;
718 return 0;
719}
720
1e5678d0 721int is_kernel_thread(pid_t pid) {
49aa47c7 722 const char *p;
1e5678d0
LP
723 size_t count;
724 char c;
725 bool eof;
726 FILE *f;
727
728 if (pid == 0)
729 return 0;
730
49aa47c7 731 assert(pid > 0);
1e5678d0 732
49aa47c7
LP
733 p = procfs_file_alloca(pid, "cmdline");
734 f = fopen(p, "re");
1e5678d0
LP
735 if (!f)
736 return -errno;
737
738 count = fread(&c, 1, 1, f);
739 eof = feof(f);
740 fclose(f);
741
742 /* Kernel threads have an empty cmdline */
743
744 if (count <= 0)
745 return eof ? 1 : -errno;
746
747 return 0;
748}
749
3a832116
SL
750int get_process_capeff(pid_t pid, char **capeff) {
751 const char *p;
3a832116
SL
752
753 assert(capeff);
754 assert(pid >= 0);
755
b68fa010 756 p = procfs_file_alloca(pid, "status");
3a832116 757
69ab8088 758 return get_status_field(p, "\nCapEff:", capeff);
3a832116 759}
49aa47c7 760
87d2c1ff 761int get_process_exe(pid_t pid, char **name) {
49aa47c7 762 const char *p;
e79f68d1
ZJS
763 char *d;
764 int r;
87d2c1ff 765
49aa47c7 766 assert(pid >= 0);
87d2c1ff
LP
767 assert(name);
768
b68fa010 769 p = procfs_file_alloca(pid, "exe");
87d2c1ff 770
e79f68d1
ZJS
771 r = readlink_malloc(p, name);
772 if (r < 0)
5b12334d 773 return r == -ENOENT ? -ESRCH : r;
e79f68d1
ZJS
774
775 d = endswith(*name, " (deleted)");
776 if (d)
777 *d = '\0';
778
779 return 0;
87d2c1ff
LP
780}
781
901c3d0d 782static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
f74e605f 783 _cleanup_fclose_ FILE *f = NULL;
9db11a99 784 char line[LINE_MAX];
49aa47c7 785 const char *p;
7e4ab3c5 786
f74e605f 787 assert(field);
7e4ab3c5
LP
788 assert(uid);
789
790 if (pid == 0)
791 return getuid();
792
49aa47c7
LP
793 p = procfs_file_alloca(pid, "status");
794 f = fopen(p, "re");
7e4ab3c5
LP
795 if (!f)
796 return -errno;
797
9db11a99 798 FOREACH_LINE(line, f, return -errno) {
f74e605f 799 char *l;
7e4ab3c5
LP
800
801 l = strstrip(line);
802
901c3d0d
LP
803 if (startswith(l, field)) {
804 l += strlen(field);
7e4ab3c5
LP
805 l += strspn(l, WHITESPACE);
806
807 l[strcspn(l, WHITESPACE)] = 0;
808
f74e605f 809 return parse_uid(l, uid);
7e4ab3c5
LP
810 }
811 }
812
f74e605f 813 return -EIO;
7e4ab3c5
LP
814}
815
901c3d0d
LP
816int get_process_uid(pid_t pid, uid_t *uid) {
817 return get_process_id(pid, "Uid:", uid);
818}
819
820int get_process_gid(pid_t pid, gid_t *gid) {
49aa47c7 821 assert_cc(sizeof(uid_t) == sizeof(gid_t));
901c3d0d
LP
822 return get_process_id(pid, "Gid:", gid);
823}
824
fab56fc5
LP
825char *strnappend(const char *s, const char *suffix, size_t b) {
826 size_t a;
44d8db9e
LP
827 char *r;
828
fab56fc5
LP
829 if (!s && !suffix)
830 return strdup("");
831
832 if (!s)
833 return strndup(suffix, b);
834
835 if (!suffix)
836 return strdup(s);
837
44d8db9e
LP
838 assert(s);
839 assert(suffix);
840
841 a = strlen(s);
aa408e77 842 if (b > ((size_t) -1) - a)
040f18ea 843 return NULL;
44d8db9e 844
040f18ea
LP
845 r = new(char, a+b+1);
846 if (!r)
44d8db9e
LP
847 return NULL;
848
849 memcpy(r, s, a);
850 memcpy(r+a, suffix, b);
851 r[a+b] = 0;
852
853 return r;
854}
87f0e418 855
fab56fc5
LP
856char *strappend(const char *s, const char *suffix) {
857 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
858}
859
849958d1 860int readlinkat_malloc(int fd, const char *p, char **ret) {
87f0e418 861 size_t l = 100;
2d2ebd6b 862 int r;
87f0e418
LP
863
864 assert(p);
2d2ebd6b 865 assert(ret);
87f0e418
LP
866
867 for (;;) {
868 char *c;
869 ssize_t n;
870
2d2ebd6b
LP
871 c = new(char, l);
872 if (!c)
87f0e418
LP
873 return -ENOMEM;
874
849958d1 875 n = readlinkat(fd, p, c, l-1);
2d2ebd6b
LP
876 if (n < 0) {
877 r = -errno;
87f0e418 878 free(c);
2d2ebd6b 879 return r;
87f0e418
LP
880 }
881
882 if ((size_t) n < l-1) {
883 c[n] = 0;
2d2ebd6b 884 *ret = c;
87f0e418
LP
885 return 0;
886 }
887
888 free(c);
889 l *= 2;
890 }
891}
892
849958d1
LP
893int readlink_malloc(const char *p, char **ret) {
894 return readlinkat_malloc(AT_FDCWD, p, ret);
895}
896
2c7108c4 897int readlink_and_make_absolute(const char *p, char **r) {
1058cbf2
ZJS
898 _cleanup_free_ char *target = NULL;
899 char *k;
2c7108c4
LP
900 int j;
901
902 assert(p);
903 assert(r);
904
1058cbf2
ZJS
905 j = readlink_malloc(p, &target);
906 if (j < 0)
2c7108c4
LP
907 return j;
908
909 k = file_in_same_dir(p, target);
2c7108c4
LP
910 if (!k)
911 return -ENOMEM;
912
913 *r = k;
914 return 0;
915}
916
83096483
LP
917int readlink_and_canonicalize(const char *p, char **r) {
918 char *t, *s;
919 int j;
920
921 assert(p);
922 assert(r);
923
924 j = readlink_and_make_absolute(p, &t);
925 if (j < 0)
926 return j;
927
928 s = canonicalize_file_name(t);
929 if (s) {
930 free(t);
931 *r = s;
932 } else
933 *r = t;
934
935 path_kill_slashes(*r);
936
937 return 0;
938}
939
2a987ee8
LP
940int reset_all_signal_handlers(void) {
941 int sig;
942
943 for (sig = 1; sig < _NSIG; sig++) {
b92bea5d
ZJS
944 struct sigaction sa = {
945 .sa_handler = SIG_DFL,
946 .sa_flags = SA_RESTART,
947 };
2a987ee8
LP
948
949 if (sig == SIGKILL || sig == SIGSTOP)
950 continue;
951
2a987ee8
LP
952 /* On Linux the first two RT signals are reserved by
953 * glibc, and sigaction() will return EINVAL for them. */
954 if ((sigaction(sig, &sa, NULL) < 0))
955 if (errno != EINVAL)
956 return -errno;
957 }
958
8e274523 959 return 0;
2a987ee8 960}
4a72ff34
LP
961
962char *strstrip(char *s) {
57a8eca8 963 char *e;
4a72ff34
LP
964
965 /* Drops trailing whitespace. Modifies the string in
966 * place. Returns pointer to first non-space character */
967
968 s += strspn(s, WHITESPACE);
969
57a8eca8
LP
970 for (e = strchr(s, 0); e > s; e --)
971 if (!strchr(WHITESPACE, e[-1]))
972 break;
4a72ff34 973
57a8eca8 974 *e = 0;
4a72ff34
LP
975
976 return s;
4a72ff34
LP
977}
978
ee9b5e01
LP
979char *delete_chars(char *s, const char *bad) {
980 char *f, *t;
981
982 /* Drops all whitespace, regardless where in the string */
983
984 for (f = s, t = s; *f; f++) {
985 if (strchr(bad, *f))
986 continue;
987
988 *(t++) = *f;
989 }
990
991 *t = 0;
992
993 return s;
994}
995
4a72ff34
LP
996char *file_in_same_dir(const char *path, const char *filename) {
997 char *e, *r;
998 size_t k;
999
1000 assert(path);
1001 assert(filename);
1002
1003 /* This removes the last component of path and appends
1004 * filename, unless the latter is absolute anyway or the
1005 * former isn't */
1006
1007 if (path_is_absolute(filename))
1008 return strdup(filename);
1009
1010 if (!(e = strrchr(path, '/')))
1011 return strdup(filename);
1012
1013 k = strlen(filename);
1014 if (!(r = new(char, e-path+1+k+1)))
1015 return NULL;
1016
1017 memcpy(r, path, e-path+1);
1018 memcpy(r+(e-path)+1, filename, k+1);
1019
1020 return r;
1021}
fb624d04 1022
c32dd69b
LP
1023int rmdir_parents(const char *path, const char *stop) {
1024 size_t l;
1025 int r = 0;
1026
1027 assert(path);
1028 assert(stop);
1029
1030 l = strlen(path);
1031
1032 /* Skip trailing slashes */
1033 while (l > 0 && path[l-1] == '/')
1034 l--;
1035
1036 while (l > 0) {
1037 char *t;
1038
1039 /* Skip last component */
1040 while (l > 0 && path[l-1] != '/')
1041 l--;
1042
1043 /* Skip trailing slashes */
1044 while (l > 0 && path[l-1] == '/')
1045 l--;
1046
1047 if (l <= 0)
1048 break;
1049
1050 if (!(t = strndup(path, l)))
1051 return -ENOMEM;
1052
1053 if (path_startswith(stop, t)) {
1054 free(t);
1055 return 0;
1056 }
1057
1058 r = rmdir(t);
1059 free(t);
1060
1061 if (r < 0)
1062 if (errno != ENOENT)
1063 return -errno;
1064 }
1065
1066 return 0;
1067}
1068
fb624d04
LP
1069char hexchar(int x) {
1070 static const char table[16] = "0123456789abcdef";
1071
1072 return table[x & 15];
1073}
4fe88d28
LP
1074
1075int unhexchar(char c) {
1076
1077 if (c >= '0' && c <= '9')
1078 return c - '0';
1079
1080 if (c >= 'a' && c <= 'f')
ea430986 1081 return c - 'a' + 10;
4fe88d28
LP
1082
1083 if (c >= 'A' && c <= 'F')
ea430986 1084 return c - 'A' + 10;
4fe88d28 1085
7e8185ef 1086 return -EINVAL;
4fe88d28
LP
1087}
1088
66e35261
LP
1089char *hexmem(const void *p, size_t l) {
1090 char *r, *z;
1091 const uint8_t *x;
1092
1093 z = r = malloc(l * 2 + 1);
1094 if (!r)
1095 return NULL;
1096
1097 for (x = p; x < (const uint8_t*) p + l; x++) {
1098 *(z++) = hexchar(*x >> 4);
1099 *(z++) = hexchar(*x & 15);
1100 }
1101
1102 *z = 0;
1103 return r;
1104}
1105
2181a7f5
LP
1106void *unhexmem(const char *p, size_t l) {
1107 uint8_t *r, *z;
1108 const char *x;
1109
1110 assert(p);
1111
1112 z = r = malloc((l + 1) / 2 + 1);
1113 if (!r)
1114 return NULL;
1115
1116 for (x = p; x < p + l; x += 2) {
1117 int a, b;
1118
1119 a = unhexchar(x[0]);
1120 if (x+1 < p + l)
1121 b = unhexchar(x[1]);
1122 else
1123 b = 0;
1124
1125 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1126 }
1127
1128 *z = 0;
1129 return r;
1130}
1131
4fe88d28
LP
1132char octchar(int x) {
1133 return '0' + (x & 7);
1134}
1135
1136int unoctchar(char c) {
1137
1138 if (c >= '0' && c <= '7')
1139 return c - '0';
1140
7e8185ef 1141 return -EINVAL;
4fe88d28
LP
1142}
1143
5af98f82
LP
1144char decchar(int x) {
1145 return '0' + (x % 10);
1146}
1147
1148int undecchar(char c) {
1149
1150 if (c >= '0' && c <= '9')
1151 return c - '0';
1152
7e8185ef 1153 return -EINVAL;
5af98f82
LP
1154}
1155
4fe88d28
LP
1156char *cescape(const char *s) {
1157 char *r, *t;
1158 const char *f;
1159
1160 assert(s);
1161
1162 /* Does C style string escaping. */
1163
f8e2fb7b
LP
1164 r = new(char, strlen(s)*4 + 1);
1165 if (!r)
4fe88d28
LP
1166 return NULL;
1167
1168 for (f = s, t = r; *f; f++)
1169
1170 switch (*f) {
1171
1172 case '\a':
1173 *(t++) = '\\';
1174 *(t++) = 'a';
1175 break;
1176 case '\b':
1177 *(t++) = '\\';
1178 *(t++) = 'b';
1179 break;
1180 case '\f':
1181 *(t++) = '\\';
1182 *(t++) = 'f';
1183 break;
1184 case '\n':
1185 *(t++) = '\\';
1186 *(t++) = 'n';
1187 break;
1188 case '\r':
1189 *(t++) = '\\';
1190 *(t++) = 'r';
1191 break;
1192 case '\t':
1193 *(t++) = '\\';
1194 *(t++) = 't';
1195 break;
1196 case '\v':
1197 *(t++) = '\\';
1198 *(t++) = 'v';
1199 break;
1200 case '\\':
1201 *(t++) = '\\';
1202 *(t++) = '\\';
1203 break;
1204 case '"':
1205 *(t++) = '\\';
1206 *(t++) = '"';
1207 break;
1208 case '\'':
1209 *(t++) = '\\';
1210 *(t++) = '\'';
1211 break;
1212
1213 default:
1214 /* For special chars we prefer octal over
1215 * hexadecimal encoding, simply because glib's
1216 * g_strescape() does the same */
1217 if ((*f < ' ') || (*f >= 127)) {
1218 *(t++) = '\\';
1219 *(t++) = octchar((unsigned char) *f >> 6);
1220 *(t++) = octchar((unsigned char) *f >> 3);
1221 *(t++) = octchar((unsigned char) *f);
1222 } else
1223 *(t++) = *f;
1224 break;
1225 }
1226
1227 *t = 0;
1228
1229 return r;
1230}
1231
5b4c61cd 1232char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
4fe88d28
LP
1233 char *r, *t;
1234 const char *f;
5b4c61cd 1235 size_t pl;
4fe88d28
LP
1236
1237 assert(s);
1238
5b4c61cd
LP
1239 /* Undoes C style string escaping, and optionally prefixes it. */
1240
1241 pl = prefix ? strlen(prefix) : 0;
4fe88d28 1242
5b4c61cd 1243 r = new(char, pl+length+1);
7f110ff9 1244 if (!r)
1e2fd62d 1245 return NULL;
4fe88d28 1246
5b4c61cd
LP
1247 if (prefix)
1248 memcpy(r, prefix, pl);
1249
1250 for (f = s, t = r + pl; f < s + length; f++) {
4fe88d28
LP
1251
1252 if (*f != '\\') {
1253 *(t++) = *f;
1254 continue;
1255 }
1256
1257 f++;
1258
1259 switch (*f) {
1260
1261 case 'a':
1262 *(t++) = '\a';
1263 break;
1264 case 'b':
1265 *(t++) = '\b';
1266 break;
1267 case 'f':
1268 *(t++) = '\f';
1269 break;
1270 case 'n':
1271 *(t++) = '\n';
1272 break;
1273 case 'r':
1274 *(t++) = '\r';
1275 break;
1276 case 't':
1277 *(t++) = '\t';
1278 break;
1279 case 'v':
1280 *(t++) = '\v';
1281 break;
1282 case '\\':
1283 *(t++) = '\\';
1284 break;
1285 case '"':
1286 *(t++) = '"';
1287 break;
1288 case '\'':
1289 *(t++) = '\'';
1290 break;
1291
e167fb86
LP
1292 case 's':
1293 /* This is an extension of the XDG syntax files */
1294 *(t++) = ' ';
1295 break;
1296
4fe88d28
LP
1297 case 'x': {
1298 /* hexadecimal encoding */
1299 int a, b;
1300
7f110ff9
LP
1301 a = unhexchar(f[1]);
1302 b = unhexchar(f[2]);
1303
e0a33e7b 1304 if (a < 0 || b < 0 || (a == 0 && b == 0)) {
4fe88d28
LP
1305 /* Invalid escape code, let's take it literal then */
1306 *(t++) = '\\';
1307 *(t++) = 'x';
1308 } else {
1309 *(t++) = (char) ((a << 4) | b);
1310 f += 2;
1311 }
1312
1313 break;
1314 }
1315
1316 case '0':
1317 case '1':
1318 case '2':
1319 case '3':
1320 case '4':
1321 case '5':
1322 case '6':
1323 case '7': {
1324 /* octal encoding */
1325 int a, b, c;
1326
7f110ff9
LP
1327 a = unoctchar(f[0]);
1328 b = unoctchar(f[1]);
1329 c = unoctchar(f[2]);
1330
e0a33e7b 1331 if (a < 0 || b < 0 || c < 0 || (a == 0 && b == 0 && c == 0)) {
4fe88d28
LP
1332 /* Invalid escape code, let's take it literal then */
1333 *(t++) = '\\';
1334 *(t++) = f[0];
1335 } else {
1336 *(t++) = (char) ((a << 6) | (b << 3) | c);
1337 f += 2;
1338 }
1339
1340 break;
1341 }
1342
1343 case 0:
1344 /* premature end of string.*/
1345 *(t++) = '\\';
1346 goto finish;
1347
1348 default:
1349 /* Invalid escape code, let's take it literal then */
1350 *(t++) = '\\';
f3d4cc01 1351 *(t++) = *f;
4fe88d28
LP
1352 break;
1353 }
1354 }
1355
1356finish:
1357 *t = 0;
1358 return r;
1359}
1360
5b4c61cd
LP
1361char *cunescape_length(const char *s, size_t length) {
1362 return cunescape_length_with_prefix(s, length, NULL);
1363}
1364
6febfd0d 1365char *cunescape(const char *s) {
5b4c61cd
LP
1366 assert(s);
1367
6febfd0d
LP
1368 return cunescape_length(s, strlen(s));
1369}
4fe88d28
LP
1370
1371char *xescape(const char *s, const char *bad) {
1372 char *r, *t;
1373 const char *f;
1374
1375 /* Escapes all chars in bad, in addition to \ and all special
1376 * chars, in \xFF style escaping. May be reversed with
1377 * cunescape. */
1378
08ace05b
LP
1379 r = new(char, strlen(s) * 4 + 1);
1380 if (!r)
4fe88d28
LP
1381 return NULL;
1382
1383 for (f = s, t = r; *f; f++) {
1384
b866264a
LP
1385 if ((*f < ' ') || (*f >= 127) ||
1386 (*f == '\\') || strchr(bad, *f)) {
4fe88d28
LP
1387 *(t++) = '\\';
1388 *(t++) = 'x';
1389 *(t++) = hexchar(*f >> 4);
1390 *(t++) = hexchar(*f);
1391 } else
1392 *(t++) = *f;
1393 }
1394
1395 *t = 0;
1396
1397 return r;
1398}
1399
67d51650 1400char *ascii_strlower(char *t) {
4fe88d28
LP
1401 char *p;
1402
67d51650 1403 assert(t);
4fe88d28 1404
67d51650 1405 for (p = t; *p; p++)
4fe88d28
LP
1406 if (*p >= 'A' && *p <= 'Z')
1407 *p = *p - 'A' + 'a';
1408
67d51650 1409 return t;
4fe88d28 1410}
1dccbe19 1411
44a6b1b6 1412_pure_ static bool ignore_file_allow_backup(const char *filename) {
c85dc17b
LP
1413 assert(filename);
1414
1415 return
1416 filename[0] == '.' ||
6c78be3c 1417 streq(filename, "lost+found") ||
e472d476
LP
1418 streq(filename, "aquota.user") ||
1419 streq(filename, "aquota.group") ||
c85dc17b
LP
1420 endswith(filename, ".rpmnew") ||
1421 endswith(filename, ".rpmsave") ||
1422 endswith(filename, ".rpmorig") ||
1423 endswith(filename, ".dpkg-old") ||
1424 endswith(filename, ".dpkg-new") ||
0cdfd26e 1425 endswith(filename, ".dpkg-tmp") ||
c85dc17b
LP
1426 endswith(filename, ".swp");
1427}
1428
a228a22f
LP
1429bool ignore_file(const char *filename) {
1430 assert(filename);
1431
1432 if (endswith(filename, "~"))
93f1a063 1433 return true;
a228a22f
LP
1434
1435 return ignore_file_allow_backup(filename);
1436}
1437
3a0ecb08 1438int fd_nonblock(int fd, bool nonblock) {
be8f4e9e 1439 int flags, nflags;
3a0ecb08
LP
1440
1441 assert(fd >= 0);
1442
be8f4e9e
LP
1443 flags = fcntl(fd, F_GETFL, 0);
1444 if (flags < 0)
3a0ecb08
LP
1445 return -errno;
1446
1447 if (nonblock)
be8f4e9e 1448 nflags = flags | O_NONBLOCK;
3a0ecb08 1449 else
be8f4e9e
LP
1450 nflags = flags & ~O_NONBLOCK;
1451
1452 if (nflags == flags)
1453 return 0;
3a0ecb08 1454
34b42c96 1455 if (fcntl(fd, F_SETFL, nflags) < 0)
3a0ecb08
LP
1456 return -errno;
1457
1458 return 0;
1459}
1460
1461int fd_cloexec(int fd, bool cloexec) {
be8f4e9e 1462 int flags, nflags;
3a0ecb08
LP
1463
1464 assert(fd >= 0);
1465
be8f4e9e
LP
1466 flags = fcntl(fd, F_GETFD, 0);
1467 if (flags < 0)
3a0ecb08
LP
1468 return -errno;
1469
1470 if (cloexec)
be8f4e9e 1471 nflags = flags | FD_CLOEXEC;
3a0ecb08 1472 else
be8f4e9e
LP
1473 nflags = flags & ~FD_CLOEXEC;
1474
1475 if (nflags == flags)
1476 return 0;
3a0ecb08 1477
34b42c96 1478 if (fcntl(fd, F_SETFD, nflags) < 0)
3a0ecb08
LP
1479 return -errno;
1480
1481 return 0;
1482}
1483
44a6b1b6 1484_pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
b19be9eb
LP
1485 unsigned i;
1486
1487 assert(n_fdset == 0 || fdset);
1488
1489 for (i = 0; i < n_fdset; i++)
1490 if (fdset[i] == fd)
1491 return true;
1492
1493 return false;
1494}
1495
a0d40ac5 1496int close_all_fds(const int except[], unsigned n_except) {
e1d75803 1497 _cleanup_closedir_ DIR *d = NULL;
a0d40ac5
LP
1498 struct dirent *de;
1499 int r = 0;
1500
b19be9eb
LP
1501 assert(n_except == 0 || except);
1502
1503 d = opendir("/proc/self/fd");
1504 if (!d) {
1505 int fd;
1506 struct rlimit rl;
1507
1508 /* When /proc isn't available (for example in chroots)
1509 * the fallback is brute forcing through the fd
1510 * table */
1511
1512 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1513 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1514
1515 if (fd_in_set(fd, except, n_except))
1516 continue;
1517
1518 if (close_nointr(fd) < 0)
1519 if (errno != EBADF && r == 0)
1520 r = -errno;
1521 }
1522
1523 return r;
1524 }
a0d40ac5
LP
1525
1526 while ((de = readdir(d))) {
a7610064 1527 int fd = -1;
a0d40ac5 1528
a16e1123 1529 if (ignore_file(de->d_name))
a0d40ac5
LP
1530 continue;
1531
720ce21d
LP
1532 if (safe_atoi(de->d_name, &fd) < 0)
1533 /* Let's better ignore this, just in case */
1534 continue;
a0d40ac5
LP
1535
1536 if (fd < 3)
1537 continue;
1538
1539 if (fd == dirfd(d))
1540 continue;
1541
b19be9eb
LP
1542 if (fd_in_set(fd, except, n_except))
1543 continue;
a0d40ac5 1544
720ce21d 1545 if (close_nointr(fd) < 0) {
2f357920 1546 /* Valgrind has its own FD and doesn't want to have it closed */
720ce21d
LP
1547 if (errno != EBADF && r == 0)
1548 r = -errno;
2f357920 1549 }
a0d40ac5
LP
1550 }
1551
a0d40ac5
LP
1552 return r;
1553}
1554
db12775d
LP
1555bool chars_intersect(const char *a, const char *b) {
1556 const char *p;
1557
1558 /* Returns true if any of the chars in a are in b. */
1559 for (p = a; *p; p++)
1560 if (strchr(b, *p))
1561 return true;
1562
1563 return false;
1564}
1565
42856c10 1566bool fstype_is_network(const char *fstype) {
a05f97b3
LP
1567 static const char table[] =
1568 "cifs\0"
1569 "smbfs\0"
da92ca5e 1570 "sshfs\0"
a05f97b3 1571 "ncpfs\0"
dac70dc7 1572 "ncp\0"
a05f97b3
LP
1573 "nfs\0"
1574 "nfs4\0"
1575 "gfs\0"
67608cad
LP
1576 "gfs2\0"
1577 "glusterfs\0";
1578
1579 const char *x;
1580
1581 x = startswith(fstype, "fuse.");
1582 if (x)
1583 fstype = x;
42856c10 1584
a05f97b3 1585 return nulstr_contains(table, fstype);
42856c10
LP
1586}
1587
601f6a1e 1588int chvt(int vt) {
a05f97b3 1589 _cleanup_close_ int fd;
601f6a1e 1590
a05f97b3
LP
1591 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1592 if (fd < 0)
601f6a1e
LP
1593 return -errno;
1594
1595 if (vt < 0) {
1596 int tiocl[2] = {
1597 TIOCL_GETKMSGREDIRECT,
1598 0
1599 };
1600
a05f97b3
LP
1601 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1602 return -errno;
601f6a1e
LP
1603
1604 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1605 }
1606
1607 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
a05f97b3 1608 return -errno;
601f6a1e 1609
a05f97b3 1610 return 0;
601f6a1e
LP
1611}
1612
8f2d43a0 1613int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
80876c20 1614 struct termios old_termios, new_termios;
e0a33e7b 1615 char c, line[LINE_MAX];
80876c20
LP
1616
1617 assert(f);
1618 assert(ret);
1619
1620 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1621 new_termios = old_termios;
1622
1623 new_termios.c_lflag &= ~ICANON;
1624 new_termios.c_cc[VMIN] = 1;
1625 new_termios.c_cc[VTIME] = 0;
1626
1627 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1628 size_t k;
1629
3a43da28 1630 if (t != USEC_INFINITY) {
8f2d43a0
LP
1631 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1632 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1633 return -ETIMEDOUT;
1634 }
1635 }
1636
80876c20
LP
1637 k = fread(&c, 1, 1, f);
1638
1639 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1640
1641 if (k <= 0)
1642 return -EIO;
1643
1644 if (need_nl)
1645 *need_nl = c != '\n';
1646
1647 *ret = c;
1648 return 0;
1649 }
1650 }
1651
3a43da28 1652 if (t != USEC_INFINITY) {
8f2d43a0
LP
1653 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1654 return -ETIMEDOUT;
e0a33e7b 1655 }
8f2d43a0 1656
3a8a9163 1657 errno = 0;
8f2d43a0 1658 if (!fgets(line, sizeof(line), f))
3a8a9163 1659 return errno ? -errno : -EIO;
80876c20
LP
1660
1661 truncate_nl(line);
1662
1663 if (strlen(line) != 1)
1664 return -EBADMSG;
1665
1666 if (need_nl)
1667 *need_nl = false;
1668
1669 *ret = line[0];
1670 return 0;
1671}
1672
418b9be5 1673int ask_char(char *ret, const char *replies, const char *text, ...) {
e0a33e7b 1674 int r;
1b39d4b9 1675
80876c20
LP
1676 assert(ret);
1677 assert(replies);
1678 assert(text);
1679
1680 for (;;) {
1681 va_list ap;
1682 char c;
80876c20
LP
1683 bool need_nl = true;
1684
8481248b 1685 if (on_tty())
c1072ea0 1686 fputs(ANSI_HIGHLIGHT_ON, stdout);
b1b2dc0c 1687
80876c20
LP
1688 va_start(ap, text);
1689 vprintf(text, ap);
1690 va_end(ap);
1691
8481248b 1692 if (on_tty())
c1072ea0 1693 fputs(ANSI_HIGHLIGHT_OFF, stdout);
b1b2dc0c 1694
80876c20
LP
1695 fflush(stdout);
1696
3a43da28 1697 r = read_one_char(stdin, &c, USEC_INFINITY, &need_nl);
8f2d43a0 1698 if (r < 0) {
80876c20
LP
1699
1700 if (r == -EBADMSG) {
1701 puts("Bad input, please try again.");
1702 continue;
1703 }
1704
1705 putchar('\n');
1706 return r;
1707 }
1708
1709 if (need_nl)
1710 putchar('\n');
1711
1712 if (strchr(replies, c)) {
1713 *ret = c;
1714 return 0;
1715 }
1716
1717 puts("Read unexpected character, please try again.");
1718 }
1719}
1720
418b9be5
LP
1721int ask_string(char **ret, const char *text, ...) {
1722 assert(ret);
1723 assert(text);
1724
1725 for (;;) {
1726 char line[LINE_MAX];
1727 va_list ap;
1728
1729 if (on_tty())
1730 fputs(ANSI_HIGHLIGHT_ON, stdout);
1731
1732 va_start(ap, text);
1733 vprintf(text, ap);
1734 va_end(ap);
1735
1736 if (on_tty())
1737 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1738
1739 fflush(stdout);
1740
1741 errno = 0;
1742 if (!fgets(line, sizeof(line), stdin))
1743 return errno ? -errno : -EIO;
1744
1745 if (!endswith(line, "\n"))
1746 putchar('\n');
1747 else {
1748 char *s;
1749
1750 if (isempty(line))
1751 continue;
1752
1753 truncate_nl(line);
1754 s = strdup(line);
1755 if (!s)
1756 return -ENOMEM;
1757
1758 *ret = s;
1759 return 0;
1760 }
1761 }
1762}
1763
512947d4 1764int reset_terminal_fd(int fd, bool switch_to_text) {
80876c20
LP
1765 struct termios termios;
1766 int r = 0;
3fe5e5d4
LP
1767
1768 /* Set terminal to some sane defaults */
80876c20
LP
1769
1770 assert(fd >= 0);
1771
eed1d0e3
LP
1772 /* We leave locked terminal attributes untouched, so that
1773 * Plymouth may set whatever it wants to set, and we don't
1774 * interfere with that. */
3fe5e5d4
LP
1775
1776 /* Disable exclusive mode, just in case */
1777 ioctl(fd, TIOCNXCL);
1778
5c0100a5 1779 /* Switch to text mode */
512947d4
MS
1780 if (switch_to_text)
1781 ioctl(fd, KDSETMODE, KD_TEXT);
5c0100a5 1782
3fe5e5d4 1783 /* Enable console unicode mode */
df465b3f 1784 ioctl(fd, KDSKBMODE, K_UNICODE);
80876c20
LP
1785
1786 if (tcgetattr(fd, &termios) < 0) {
1787 r = -errno;
1788 goto finish;
1789 }
1790
aaf694ca
LP
1791 /* We only reset the stuff that matters to the software. How
1792 * hardware is set up we don't touch assuming that somebody
1793 * else will do that for us */
1794
1795 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
80876c20
LP
1796 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1797 termios.c_oflag |= ONLCR;
1798 termios.c_cflag |= CREAD;
1799 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1800
1801 termios.c_cc[VINTR] = 03; /* ^C */
1802 termios.c_cc[VQUIT] = 034; /* ^\ */
1803 termios.c_cc[VERASE] = 0177;
1804 termios.c_cc[VKILL] = 025; /* ^X */
1805 termios.c_cc[VEOF] = 04; /* ^D */
1806 termios.c_cc[VSTART] = 021; /* ^Q */
1807 termios.c_cc[VSTOP] = 023; /* ^S */
1808 termios.c_cc[VSUSP] = 032; /* ^Z */
1809 termios.c_cc[VLNEXT] = 026; /* ^V */
1810 termios.c_cc[VWERASE] = 027; /* ^W */
1811 termios.c_cc[VREPRINT] = 022; /* ^R */
aaf694ca
LP
1812 termios.c_cc[VEOL] = 0;
1813 termios.c_cc[VEOL2] = 0;
80876c20
LP
1814
1815 termios.c_cc[VTIME] = 0;
1816 termios.c_cc[VMIN] = 1;
1817
1818 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1819 r = -errno;
1820
1821finish:
1822 /* Just in case, flush all crap out */
1823 tcflush(fd, TCIOFLUSH);
1824
1825 return r;
1826}
1827
6ea832a2 1828int reset_terminal(const char *name) {
03e334a1 1829 _cleanup_close_ int fd = -1;
6ea832a2
LP
1830
1831 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1832 if (fd < 0)
1833 return fd;
1834
03e334a1 1835 return reset_terminal_fd(fd, true);
6ea832a2
LP
1836}
1837
80876c20
LP
1838int open_terminal(const char *name, int mode) {
1839 int fd, r;
f73f76ac 1840 unsigned c = 0;
80876c20 1841
f73f76ac
LP
1842 /*
1843 * If a TTY is in the process of being closed opening it might
1844 * cause EIO. This is horribly awful, but unlikely to be
1845 * changed in the kernel. Hence we work around this problem by
1846 * retrying a couple of times.
1847 *
1848 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1849 */
1850
dd94c17e
LP
1851 assert(!(mode & O_CREAT));
1852
f73f76ac 1853 for (;;) {
dd94c17e 1854 fd = open(name, mode, 0);
af6da548 1855 if (fd >= 0)
f73f76ac
LP
1856 break;
1857
1858 if (errno != EIO)
1859 return -errno;
1860
af6da548 1861 /* Max 1s in total */
f73f76ac
LP
1862 if (c >= 20)
1863 return -errno;
1864
1865 usleep(50 * USEC_PER_MSEC);
1866 c++;
1867 }
1868
1869 if (fd < 0)
80876c20
LP
1870 return -errno;
1871
af6da548
LP
1872 r = isatty(fd);
1873 if (r < 0) {
03e334a1 1874 safe_close(fd);
80876c20
LP
1875 return -errno;
1876 }
1877
1878 if (!r) {
03e334a1 1879 safe_close(fd);
80876c20
LP
1880 return -ENOTTY;
1881 }
1882
1883 return fd;
1884}
1885
1886int flush_fd(int fd) {
b92bea5d
ZJS
1887 struct pollfd pollfd = {
1888 .fd = fd,
1889 .events = POLLIN,
1890 };
80876c20
LP
1891
1892 for (;;) {
20c03b7b 1893 char buf[LINE_MAX];
80876c20
LP
1894 ssize_t l;
1895 int r;
1896
e62d8c39
ZJS
1897 r = poll(&pollfd, 1, 0);
1898 if (r < 0) {
80876c20
LP
1899 if (errno == EINTR)
1900 continue;
1901
1902 return -errno;
80876c20 1903
e62d8c39 1904 } else if (r == 0)
80876c20
LP
1905 return 0;
1906
e62d8c39
ZJS
1907 l = read(fd, buf, sizeof(buf));
1908 if (l < 0) {
80876c20
LP
1909
1910 if (errno == EINTR)
1911 continue;
1912
1913 if (errno == EAGAIN)
1914 return 0;
1915
1916 return -errno;
e62d8c39 1917 } else if (l == 0)
80876c20
LP
1918 return 0;
1919 }
1920}
1921
af6da548
LP
1922int acquire_terminal(
1923 const char *name,
1924 bool fail,
1925 bool force,
1926 bool ignore_tiocstty_eperm,
1927 usec_t timeout) {
1928
4a0ff478 1929 int fd = -1, notify = -1, r = 0, wd = -1;
af6da548 1930 usec_t ts = 0;
80876c20
LP
1931
1932 assert(name);
1933
1934 /* We use inotify to be notified when the tty is closed. We
1935 * create the watch before checking if we can actually acquire
1936 * it, so that we don't lose any event.
1937 *
1938 * Note: strictly speaking this actually watches for the
1939 * device being closed, it does *not* really watch whether a
1940 * tty loses its controlling process. However, unless some
1941 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1942 * its tty otherwise this will not become a problem. As long
1943 * as the administrator makes sure not configure any service
1944 * on the same tty as an untrusted user this should not be a
1945 * problem. (Which he probably should not do anyway.) */
1946
3a43da28 1947 if (timeout != USEC_INFINITY)
af6da548
LP
1948 ts = now(CLOCK_MONOTONIC);
1949
80876c20 1950 if (!fail && !force) {
3a43da28 1951 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
af6da548 1952 if (notify < 0) {
80876c20
LP
1953 r = -errno;
1954 goto fail;
1955 }
1956
af6da548
LP
1957 wd = inotify_add_watch(notify, name, IN_CLOSE);
1958 if (wd < 0) {
80876c20
LP
1959 r = -errno;
1960 goto fail;
1961 }
1962 }
1963
1964 for (;;) {
b92bea5d
ZJS
1965 struct sigaction sa_old, sa_new = {
1966 .sa_handler = SIG_IGN,
1967 .sa_flags = SA_RESTART,
1968 };
1969
af6da548
LP
1970 if (notify >= 0) {
1971 r = flush_fd(notify);
1972 if (r < 0)
e3d1855b 1973 goto fail;
af6da548 1974 }
80876c20
LP
1975
1976 /* We pass here O_NOCTTY only so that we can check the return
1977 * value TIOCSCTTY and have a reliable way to figure out if we
1978 * successfully became the controlling process of the tty */
af6da548
LP
1979 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1980 if (fd < 0)
6ea832a2 1981 return fd;
80876c20 1982
32c4bef8
LP
1983 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1984 * if we already own the tty. */
32c4bef8
LP
1985 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1986
80876c20 1987 /* First, try to get the tty */
32c4bef8
LP
1988 if (ioctl(fd, TIOCSCTTY, force) < 0)
1989 r = -errno;
1990
1991 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
21de3988
LP
1992
1993 /* Sometimes it makes sense to ignore TIOCSCTTY
1994 * returning EPERM, i.e. when very likely we already
1995 * are have this controlling terminal. */
32c4bef8 1996 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
21de3988
LP
1997 r = 0;
1998
32c4bef8 1999 if (r < 0 && (force || fail || r != -EPERM)) {
80876c20
LP
2000 goto fail;
2001 }
2002
2003 if (r >= 0)
2004 break;
2005
2006 assert(!fail);
2007 assert(!force);
2008 assert(notify >= 0);
2009
2010 for (;;) {
f601daa7 2011 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
80876c20 2012 ssize_t l;
f601daa7 2013 struct inotify_event *e;
80876c20 2014
3a43da28 2015 if (timeout != USEC_INFINITY) {
af6da548
LP
2016 usec_t n;
2017
2018 n = now(CLOCK_MONOTONIC);
2019 if (ts + timeout < n) {
2020 r = -ETIMEDOUT;
2021 goto fail;
2022 }
2023
2024 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2025 if (r < 0)
2026 goto fail;
2027
2028 if (r == 0) {
2029 r = -ETIMEDOUT;
2030 goto fail;
2031 }
2032 }
2033
2034 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2035 if (l < 0) {
80876c20 2036
af6da548 2037 if (errno == EINTR || errno == EAGAIN)
f601daa7
LP
2038 continue;
2039
2040 r = -errno;
2041 goto fail;
2042 }
2043
2044 e = (struct inotify_event*) inotify_buffer;
80876c20 2045
f601daa7
LP
2046 while (l > 0) {
2047 size_t step;
80876c20 2048
f601daa7 2049 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
80876c20 2050 r = -EIO;
f601daa7
LP
2051 goto fail;
2052 }
80876c20 2053
f601daa7
LP
2054 step = sizeof(struct inotify_event) + e->len;
2055 assert(step <= (size_t) l);
80876c20 2056
f601daa7
LP
2057 e = (struct inotify_event*) ((uint8_t*) e + step);
2058 l -= step;
80876c20
LP
2059 }
2060
2061 break;
2062 }
2063
2064 /* We close the tty fd here since if the old session
2065 * ended our handle will be dead. It's important that
2066 * we do this after sleeping, so that we don't enter
2067 * an endless loop. */
03e334a1 2068 safe_close(fd);
80876c20
LP
2069 }
2070
03e334a1 2071 safe_close(notify);
80876c20 2072
512947d4
MS
2073 r = reset_terminal_fd(fd, true);
2074 if (r < 0)
80876c20
LP
2075 log_warning("Failed to reset terminal: %s", strerror(-r));
2076
2077 return fd;
2078
2079fail:
03e334a1
LP
2080 safe_close(fd);
2081 safe_close(notify);
80876c20
LP
2082
2083 return r;
2084}
2085
2086int release_terminal(void) {
56d96fc0 2087 static const struct sigaction sa_new = {
b92bea5d
ZJS
2088 .sa_handler = SIG_IGN,
2089 .sa_flags = SA_RESTART,
2090 };
56d96fc0
LP
2091
2092 _cleanup_close_ int fd = -1;
2093 struct sigaction sa_old;
2094 int r = 0;
80876c20 2095
e62d8c39
ZJS
2096 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2097 if (fd < 0)
80876c20
LP
2098 return -errno;
2099
57cd2192
LP
2100 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2101 * by our own TIOCNOTTY */
57cd2192
LP
2102 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2103
80876c20
LP
2104 if (ioctl(fd, TIOCNOTTY) < 0)
2105 r = -errno;
2106
57cd2192
LP
2107 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2108
80876c20
LP
2109 return r;
2110}
2111
9a34ec5f
LP
2112int sigaction_many(const struct sigaction *sa, ...) {
2113 va_list ap;
2114 int r = 0, sig;
2115
2116 va_start(ap, sa);
2117 while ((sig = va_arg(ap, int)) > 0)
2118 if (sigaction(sig, sa, NULL) < 0)
2119 r = -errno;
2120 va_end(ap);
2121
2122 return r;
2123}
2124
2125int ignore_signals(int sig, ...) {
b92bea5d
ZJS
2126 struct sigaction sa = {
2127 .sa_handler = SIG_IGN,
2128 .sa_flags = SA_RESTART,
2129 };
9a34ec5f
LP
2130 va_list ap;
2131 int r = 0;
a337c6fc 2132
9a34ec5f
LP
2133 if (sigaction(sig, &sa, NULL) < 0)
2134 r = -errno;
2135
2136 va_start(ap, sig);
2137 while ((sig = va_arg(ap, int)) > 0)
2138 if (sigaction(sig, &sa, NULL) < 0)
2139 r = -errno;
2140 va_end(ap);
2141
2142 return r;
2143}
2144
2145int default_signals(int sig, ...) {
b92bea5d
ZJS
2146 struct sigaction sa = {
2147 .sa_handler = SIG_DFL,
2148 .sa_flags = SA_RESTART,
2149 };
9a34ec5f
LP
2150 va_list ap;
2151 int r = 0;
2152
9a34ec5f
LP
2153 if (sigaction(sig, &sa, NULL) < 0)
2154 r = -errno;
2155
2156 va_start(ap, sig);
2157 while ((sig = va_arg(ap, int)) > 0)
2158 if (sigaction(sig, &sa, NULL) < 0)
2159 r = -errno;
2160 va_end(ap);
2161
2162 return r;
a337c6fc
LP
2163}
2164
3d94f76c 2165void safe_close_pair(int p[]) {
8d567588
LP
2166 assert(p);
2167
3d94f76c
LP
2168 if (p[0] == p[1]) {
2169 /* Special case pairs which use the same fd in both
2170 * directions... */
2171 p[0] = p[1] = safe_close(p[0]);
2172 return;
8d567588
LP
2173 }
2174
3d94f76c
LP
2175 p[0] = safe_close(p[0]);
2176 p[1] = safe_close(p[1]);
8d567588
LP
2177}
2178
eb22ac37 2179ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
7d5dd5e0 2180 uint8_t *p = buf;
8d567588
LP
2181 ssize_t n = 0;
2182
2183 assert(fd >= 0);
2184 assert(buf);
2185
8d567588
LP
2186 while (nbytes > 0) {
2187 ssize_t k;
2188
7d5dd5e0
LP
2189 k = read(fd, p, nbytes);
2190 if (k < 0 && errno == EINTR)
2191 continue;
8d567588 2192
7d5dd5e0 2193 if (k < 0 && errno == EAGAIN && do_poll) {
8d567588 2194
7d5dd5e0
LP
2195 /* We knowingly ignore any return value here,
2196 * and expect that any error/EOF is reported
2197 * via read() */
8d567588 2198
3a43da28 2199 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
7d5dd5e0
LP
2200 continue;
2201 }
8d567588 2202
7d5dd5e0 2203 if (k <= 0)
8d567588 2204 return n > 0 ? n : (k < 0 ? -errno : 0);
8d567588
LP
2205
2206 p += k;
2207 nbytes -= k;
2208 n += k;
2209 }
2210
2211 return n;
2212}
2213
eb22ac37 2214ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
7d5dd5e0 2215 const uint8_t *p = buf;
eb22ac37
LP
2216 ssize_t n = 0;
2217
2218 assert(fd >= 0);
2219 assert(buf);
2220
eb22ac37
LP
2221 while (nbytes > 0) {
2222 ssize_t k;
2223
fe652127 2224 k = write(fd, p, nbytes);
7d5dd5e0
LP
2225 if (k < 0 && errno == EINTR)
2226 continue;
eb22ac37 2227
7d5dd5e0 2228 if (k < 0 && errno == EAGAIN && do_poll) {
eb22ac37 2229
7d5dd5e0
LP
2230 /* We knowingly ignore any return value here,
2231 * and expect that any error/EOF is reported
2232 * via write() */
eb22ac37 2233
3a43da28 2234 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
7d5dd5e0
LP
2235 continue;
2236 }
eb22ac37 2237
7d5dd5e0 2238 if (k <= 0)
eb22ac37 2239 return n > 0 ? n : (k < 0 ? -errno : 0);
eb22ac37
LP
2240
2241 p += k;
2242 nbytes -= k;
2243 n += k;
2244 }
2245
2246 return n;
2247}
2248
5556b5fe
LP
2249int parse_size(const char *t, off_t base, off_t *size) {
2250
2251 /* Soo, sometimes we want to parse IEC binary suffxies, and
2252 * sometimes SI decimal suffixes. This function can parse
2253 * both. Which one is the right way depends on the
2254 * context. Wikipedia suggests that SI is customary for
2255 * hardrware metrics and network speeds, while IEC is
2256 * customary for most data sizes used by software and volatile
2257 * (RAM) memory. Hence be careful which one you pick!
2258 *
2259 * In either case we use just K, M, G as suffix, and not Ki,
2260 * Mi, Gi or so (as IEC would suggest). That's because that's
2261 * frickin' ugly. But this means you really need to make sure
2262 * to document which base you are parsing when you use this
2263 * call. */
2264
2265 struct table {
ab1f0633 2266 const char *suffix;
b32ff512 2267 unsigned long long factor;
5556b5fe
LP
2268 };
2269
2270 static const struct table iec[] = {
32895bb3 2271 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
840292be
ZJS
2272 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2273 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2274 { "G", 1024ULL*1024ULL*1024ULL },
2275 { "M", 1024ULL*1024ULL },
2276 { "K", 1024ULL },
2277 { "B", 1 },
ab1f0633
LP
2278 { "", 1 },
2279 };
2280
5556b5fe 2281 static const struct table si[] = {
5556b5fe 2282 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
840292be
ZJS
2283 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2284 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2285 { "G", 1000ULL*1000ULL*1000ULL },
2286 { "M", 1000ULL*1000ULL },
2287 { "K", 1000ULL },
2288 { "B", 1 },
5556b5fe
LP
2289 { "", 1 },
2290 };
2291
2292 const struct table *table;
ab1f0633 2293 const char *p;
b32ff512 2294 unsigned long long r = 0;
840292be 2295 unsigned n_entries, start_pos = 0;
ab1f0633
LP
2296
2297 assert(t);
5556b5fe
LP
2298 assert(base == 1000 || base == 1024);
2299 assert(size);
2300
2301 if (base == 1000) {
2302 table = si;
2303 n_entries = ELEMENTSOF(si);
2304 } else {
2305 table = iec;
2306 n_entries = ELEMENTSOF(iec);
2307 }
ab1f0633
LP
2308
2309 p = t;
2310 do {
2311 long long l;
9480794b
ZJS
2312 unsigned long long l2;
2313 double frac = 0;
ab1f0633
LP
2314 char *e;
2315 unsigned i;
2316
2317 errno = 0;
2318 l = strtoll(p, &e, 10);
2319
8333c77e 2320 if (errno > 0)
ab1f0633
LP
2321 return -errno;
2322
2323 if (l < 0)
2324 return -ERANGE;
2325
2326 if (e == p)
2327 return -EINVAL;
2328
9480794b
ZJS
2329 if (*e == '.') {
2330 e++;
2331 if (*e >= '0' && *e <= '9') {
2332 char *e2;
2333
2334 /* strotoull itself would accept space/+/- */
2335 l2 = strtoull(e, &e2, 10);
2336
2337 if (errno == ERANGE)
2338 return -errno;
2339
2340 /* Ignore failure. E.g. 10.M is valid */
2341 frac = l2;
2342 for (; e < e2; e++)
2343 frac /= 10;
2344 }
2345 }
2346
ab1f0633
LP
2347 e += strspn(e, WHITESPACE);
2348
840292be 2349 for (i = start_pos; i < n_entries; i++)
ab1f0633 2350 if (startswith(e, table[i].suffix)) {
b32ff512 2351 unsigned long long tmp;
9480794b 2352 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
b32ff512 2353 return -ERANGE;
9480794b 2354 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
b32ff512
ZJS
2355 if (tmp > ULLONG_MAX - r)
2356 return -ERANGE;
2357
2358 r += tmp;
2359 if ((unsigned long long) (off_t) r != r)
2360 return -ERANGE;
2361
ab1f0633 2362 p = e + strlen(table[i].suffix);
840292be
ZJS
2363
2364 start_pos = i + 1;
ab1f0633
LP
2365 break;
2366 }
2367
5556b5fe 2368 if (i >= n_entries)
ab1f0633
LP
2369 return -EINVAL;
2370
b32ff512 2371 } while (*p);
ab1f0633 2372
5556b5fe 2373 *size = r;
ab1f0633
LP
2374
2375 return 0;
2376}
2377
843d2643
LP
2378int make_stdio(int fd) {
2379 int r, s, t;
2380
2381 assert(fd >= 0);
2382
73836c5c
LP
2383 r = dup3(fd, STDIN_FILENO, 0);
2384 s = dup3(fd, STDOUT_FILENO, 0);
2385 t = dup3(fd, STDERR_FILENO, 0);
843d2643
LP
2386
2387 if (fd >= 3)
03e334a1 2388 safe_close(fd);
843d2643
LP
2389
2390 if (r < 0 || s < 0 || t < 0)
2391 return -errno;
2392
73836c5c 2393 /* We rely here that the new fd has O_CLOEXEC not set */
7862f62d 2394
843d2643
LP
2395 return 0;
2396}
2397
ade509ce
LP
2398int make_null_stdio(void) {
2399 int null_fd;
2400
cd3bd60a
LP
2401 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2402 if (null_fd < 0)
ade509ce
LP
2403 return -errno;
2404
2405 return make_stdio(null_fd);
2406}
2407
8407a5d0
LP
2408bool is_device_path(const char *path) {
2409
2410 /* Returns true on paths that refer to a device, either in
2411 * sysfs or in /dev */
2412
2413 return
2414 path_startswith(path, "/dev/") ||
2415 path_startswith(path, "/sys/");
2416}
2417
01f78473 2418int dir_is_empty(const char *path) {
a05f97b3 2419 _cleanup_closedir_ DIR *d;
01f78473 2420
a05f97b3
LP
2421 d = opendir(path);
2422 if (!d)
01f78473
LP
2423 return -errno;
2424
2425 for (;;) {
7d5e9c0f 2426 struct dirent *de;
01f78473 2427
3fd11280
FW
2428 errno = 0;
2429 de = readdir(d);
2430 if (!de && errno != 0)
2431 return -errno;
01f78473 2432
a05f97b3
LP
2433 if (!de)
2434 return 1;
01f78473 2435
a05f97b3
LP
2436 if (!ignore_file(de->d_name))
2437 return 0;
2438 }
01f78473
LP
2439}
2440
844ec79b
ZJS
2441char* dirname_malloc(const char *path) {
2442 char *d, *dir, *dir2;
2443
2444 d = strdup(path);
2445 if (!d)
2446 return NULL;
2447 dir = dirname(d);
2448 assert(dir);
2449
2450 if (dir != d) {
2451 dir2 = strdup(dir);
2452 free(d);
2453 return dir2;
2454 }
2455
2456 return dir;
2457}
2458
b89446bb 2459int dev_urandom(void *p, size_t n) {
a05f97b3 2460 _cleanup_close_ int fd;
9bf3b535 2461 ssize_t k;
d3782d60 2462
ac0930c8
LP
2463 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2464 if (fd < 0)
b89446bb 2465 return errno == ENOENT ? -ENOSYS : -errno;
d3782d60 2466
9bf3b535 2467 k = loop_read(fd, p, n, true);
b89446bb
LP
2468 if (k < 0)
2469 return (int) k;
2470 if ((size_t) k != n)
2471 return -EIO;
2472
2473 return 0;
2474}
2475
2476void random_bytes(void *p, size_t n) {
2477 static bool srand_called = false;
2478 uint8_t *q;
2479 int r;
d3782d60 2480
b89446bb
LP
2481 r = dev_urandom(p, n);
2482 if (r >= 0)
2483 return;
d3782d60 2484
b89446bb
LP
2485 /* If some idiot made /dev/urandom unavailable to us, he'll
2486 * get a PRNG instead. */
d3782d60 2487
9bf3b535 2488 if (!srand_called) {
b89446bb 2489 unsigned x = 0;
a3b6fafe 2490
9bf3b535
LP
2491#ifdef HAVE_SYS_AUXV_H
2492 /* The kernel provides us with a bit of entropy in
2493 * auxv, so let's try to make use of that to seed the
2494 * pseudo-random generator. It's better than
2495 * nothing... */
a3b6fafe 2496
9bf3b535
LP
2497 void *auxv;
2498
2499 auxv = (void*) getauxval(AT_RANDOM);
2500 if (auxv)
b89446bb 2501 x ^= *(unsigned*) auxv;
9bf3b535 2502#endif
a3b6fafe 2503
b89446bb
LP
2504 x ^= (unsigned) now(CLOCK_REALTIME);
2505 x ^= (unsigned) gettid();
2506
2507 srand(x);
9bf3b535
LP
2508 srand_called = true;
2509 }
a3b6fafe 2510
9bf3b535
LP
2511 for (q = p; q < (uint8_t*) p + n; q ++)
2512 *q = rand();
a3b6fafe
LP
2513}
2514
5b6319dc
LP
2515void rename_process(const char name[8]) {
2516 assert(name);
2517
5d6b1584
LP
2518 /* This is a like a poor man's setproctitle(). It changes the
2519 * comm field, argv[0], and also the glibc's internally used
2520 * name of the process. For the first one a limit of 16 chars
2521 * applies, to the second one usually one of 10 (i.e. length
2522 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2523 * "systemd"). If you pass a longer string it will be
2524 * truncated */
5b6319dc 2525
5d6b1584 2526 prctl(PR_SET_NAME, name);
5b6319dc
LP
2527
2528 if (program_invocation_name)
2529 strncpy(program_invocation_name, name, strlen(program_invocation_name));
9a0e6896
LP
2530
2531 if (saved_argc > 0) {
2532 int i;
2533
2534 if (saved_argv[0])
2535 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2536
2537 for (i = 1; i < saved_argc; i++) {
2538 if (!saved_argv[i])
2539 break;
2540
29804cc1 2541 memzero(saved_argv[i], strlen(saved_argv[i]));
9a0e6896
LP
2542 }
2543 }
5b6319dc
LP
2544}
2545
7d793605
LP
2546void sigset_add_many(sigset_t *ss, ...) {
2547 va_list ap;
2548 int sig;
2549
2550 assert(ss);
2551
2552 va_start(ap, ss);
2553 while ((sig = va_arg(ap, int)) > 0)
2554 assert_se(sigaddset(ss, sig) == 0);
2555 va_end(ap);
2556}
2557
856a5a7d
LP
2558int sigprocmask_many(int how, ...) {
2559 va_list ap;
2560 sigset_t ss;
2561 int sig;
2562
2563 assert_se(sigemptyset(&ss) == 0);
2564
2565 va_start(ap, how);
2566 while ((sig = va_arg(ap, int)) > 0)
2567 assert_se(sigaddset(&ss, sig) == 0);
2568 va_end(ap);
2569
2570 if (sigprocmask(how, &ss, NULL) < 0)
2571 return -errno;
2572
2573 return 0;
2574}
2575
ef2f1067
LP
2576char* gethostname_malloc(void) {
2577 struct utsname u;
2578
2579 assert_se(uname(&u) >= 0);
2580
344de609 2581 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
ef2f1067
LP
2582 return strdup(u.nodename);
2583
2584 return strdup(u.sysname);
2585}
2586
344de609
LP
2587bool hostname_is_set(void) {
2588 struct utsname u;
2589
2590 assert_se(uname(&u) >= 0);
2591
2592 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2593}
2594
7c5f152a 2595static char *lookup_uid(uid_t uid) {
ef2f1067 2596 long bufsize;
a05f97b3
LP
2597 char *name;
2598 _cleanup_free_ char *buf = NULL;
ef2f1067 2599 struct passwd pwbuf, *pw = NULL;
ef2f1067
LP
2600
2601 /* Shortcut things to avoid NSS lookups */
2602 if (uid == 0)
2603 return strdup("root");
2604
7c5f152a
LP
2605 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2606 if (bufsize <= 0)
ef2f1067
LP
2607 bufsize = 4096;
2608
7c5f152a
LP
2609 buf = malloc(bufsize);
2610 if (!buf)
ef2f1067
LP
2611 return NULL;
2612
a05f97b3
LP
2613 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2614 return strdup(pw->pw_name);
ef2f1067 2615
de0671ee 2616 if (asprintf(&name, UID_FMT, uid) < 0)
ef2f1067
LP
2617 return NULL;
2618
2619 return name;
2620}
2621
7c5f152a
LP
2622char* getlogname_malloc(void) {
2623 uid_t uid;
2624 struct stat st;
2625
2626 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2627 uid = st.st_uid;
2628 else
2629 uid = getuid();
2630
2631 return lookup_uid(uid);
2632}
2633
2634char *getusername_malloc(void) {
2635 const char *e;
2636
2637 e = getenv("USER");
2638 if (e)
2639 return strdup(e);
2640
2641 return lookup_uid(getuid());
2642}
2643
fc116c6a
LP
2644int getttyname_malloc(int fd, char **r) {
2645 char path[PATH_MAX], *c;
618e02c7 2646 int k;
8c6db833
LP
2647
2648 assert(r);
ef2f1067 2649
a05f97b3 2650 k = ttyname_r(fd, path, sizeof(path));
27373e44 2651 if (k > 0)
618e02c7 2652 return -k;
ef2f1067
LP
2653
2654 char_array_0(path);
2655
a05f97b3
LP
2656 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2657 if (!c)
8c6db833
LP
2658 return -ENOMEM;
2659
2660 *r = c;
2661 return 0;
2662}
2663
fc116c6a
LP
2664int getttyname_harder(int fd, char **r) {
2665 int k;
2666 char *s;
2667
a05f97b3
LP
2668 k = getttyname_malloc(fd, &s);
2669 if (k < 0)
fc116c6a
LP
2670 return k;
2671
2672 if (streq(s, "tty")) {
2673 free(s);
4d6d6518 2674 return get_ctty(0, NULL, r);
fc116c6a
LP
2675 }
2676
2677 *r = s;
2678 return 0;
2679}
2680
4d6d6518 2681int get_ctty_devnr(pid_t pid, dev_t *d) {
b4696bce
SP
2682 int r;
2683 _cleanup_free_ char *line = NULL;
2684 const char *p;
fc116c6a 2685 unsigned long ttynr;
fc116c6a 2686
49aa47c7 2687 assert(pid >= 0);
49aa47c7 2688
b4696bce
SP
2689 p = procfs_file_alloca(pid, "stat");
2690 r = read_one_line_file(p, &line);
2691 if (r < 0)
2692 return r;
fc116c6a 2693
4d6d6518
LP
2694 p = strrchr(line, ')');
2695 if (!p)
fc116c6a
LP
2696 return -EIO;
2697
2698 p++;
2699
2700 if (sscanf(p, " "
2701 "%*c " /* state */
2702 "%*d " /* ppid */
2703 "%*d " /* pgrp */
2704 "%*d " /* session */
2705 "%lu ", /* ttynr */
2706 &ttynr) != 1)
2707 return -EIO;
2708
11dc5d2b
LP
2709 if (major(ttynr) == 0 && minor(ttynr) == 0)
2710 return -ENOENT;
2711
0bee65f0
LP
2712 if (d)
2713 *d = (dev_t) ttynr;
2714
fc116c6a
LP
2715 return 0;
2716}
2717
4d6d6518 2718int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
833fce28
LP
2719 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
2720 _cleanup_free_ char *s = NULL;
2721 const char *p;
fc116c6a 2722 dev_t devnr;
833fce28 2723 int k;
fc116c6a
LP
2724
2725 assert(r);
2726
4d6d6518
LP
2727 k = get_ctty_devnr(pid, &devnr);
2728 if (k < 0)
fc116c6a
LP
2729 return k;
2730
2731 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
fc116c6a 2732
23406ce5
LP
2733 k = readlink_malloc(fn, &s);
2734 if (k < 0) {
fc116c6a
LP
2735
2736 if (k != -ENOENT)
2737 return k;
2738
46824d0e
LP
2739 /* This is an ugly hack */
2740 if (major(devnr) == 136) {
de0671ee 2741 asprintf(&b, "pts/%u", minor(devnr));
833fce28 2742 goto finish;
46824d0e
LP
2743 }
2744
fc116c6a
LP
2745 /* Probably something like the ptys which have no
2746 * symlink in /dev/char. Let's return something
2747 * vaguely useful. */
2748
23406ce5 2749 b = strdup(fn + 5);
833fce28 2750 goto finish;
fc116c6a
LP
2751 }
2752
2753 if (startswith(s, "/dev/"))
2754 p = s + 5;
2755 else if (startswith(s, "../"))
2756 p = s + 3;
2757 else
2758 p = s;
2759
2760 b = strdup(p);
fc116c6a 2761
833fce28 2762finish:
fc116c6a
LP
2763 if (!b)
2764 return -ENOMEM;
2765
2766 *r = b;
46824d0e
LP
2767 if (_devnr)
2768 *_devnr = devnr;
2769
fc116c6a
LP
2770 return 0;
2771}
2772
f56d5db9 2773int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
dede0e33 2774 _cleanup_closedir_ DIR *d = NULL;
8c6db833
LP
2775 int ret = 0;
2776
2777 assert(fd >= 0);
2778
2779 /* This returns the first error we run into, but nevertheless
7925c22a 2780 * tries to go on. This closes the passed fd. */
8c6db833 2781
d4d046e3
LP
2782 d = fdopendir(fd);
2783 if (!d) {
03e334a1 2784 safe_close(fd);
4c633005
LP
2785
2786 return errno == ENOENT ? 0 : -errno;
8c6db833
LP
2787 }
2788
2789 for (;;) {
7d5e9c0f 2790 struct dirent *de;
7925c22a
LP
2791 bool is_dir, keep_around;
2792 struct stat st;
8c6db833
LP
2793 int r;
2794
3fd11280
FW
2795 errno = 0;
2796 de = readdir(d);
dede0e33
ZJS
2797 if (!de) {
2798 if (errno != 0 && ret == 0)
3fd11280 2799 ret = -errno;
dede0e33 2800 return ret;
8c6db833
LP
2801 }
2802
8c6db833
LP
2803 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2804 continue;
2805
7925c22a
LP
2806 if (de->d_type == DT_UNKNOWN ||
2807 honour_sticky ||
2808 (de->d_type == DT_DIR && root_dev)) {
8c6db833 2809 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
4c633005 2810 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2811 ret = -errno;
2812 continue;
2813 }
2814
2815 is_dir = S_ISDIR(st.st_mode);
7925c22a
LP
2816 keep_around =
2817 honour_sticky &&
2818 (st.st_uid == 0 || st.st_uid == getuid()) &&
2819 (st.st_mode & S_ISVTX);
ad293f5a 2820 } else {
8c6db833 2821 is_dir = de->d_type == DT_DIR;
7925c22a 2822 keep_around = false;
ad293f5a 2823 }
8c6db833
LP
2824
2825 if (is_dir) {
2826 int subdir_fd;
8c6db833 2827
597f43c7 2828 /* if root_dev is set, remove subdirectories only, if device is same as dir */
7925c22a
LP
2829 if (root_dev && st.st_dev != root_dev->st_dev)
2830 continue;
8c6db833 2831
7925c22a
LP
2832 subdir_fd = openat(fd, de->d_name,
2833 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2834 if (subdir_fd < 0) {
2835 if (ret == 0 && errno != ENOENT)
2836 ret = -errno;
2837 continue;
2838 }
2839
b3d28469 2840 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
7925c22a
LP
2841 if (r < 0 && ret == 0)
2842 ret = r;
2843
2844 if (!keep_around)
2845 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
ad293f5a
LP
2846 if (ret == 0 && errno != ENOENT)
2847 ret = -errno;
2848 }
2849
2850 } else if (!only_dirs && !keep_around) {
8c6db833
LP
2851
2852 if (unlinkat(fd, de->d_name, 0) < 0) {
4c633005 2853 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2854 ret = -errno;
2855 }
2856 }
2857 }
8c6db833
LP
2858}
2859
44a6b1b6 2860_pure_ static int is_temporary_fs(struct statfs *s) {
943aad8c 2861 assert(s);
73020ab2
SL
2862
2863 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2864 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
943aad8c
ZJS
2865}
2866
f56d5db9
LP
2867int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2868 struct statfs s;
2869
2870 assert(fd >= 0);
2871
2872 if (fstatfs(fd, &s) < 0) {
03e334a1 2873 safe_close(fd);
f56d5db9
LP
2874 return -errno;
2875 }
2876
2877 /* We refuse to clean disk file systems with this call. This
2878 * is extra paranoia just to be sure we never ever remove
2879 * non-state data */
943aad8c 2880 if (!is_temporary_fs(&s)) {
f56d5db9 2881 log_error("Attempted to remove disk file system, and we can't allow that.");
03e334a1 2882 safe_close(fd);
f56d5db9
LP
2883 return -EPERM;
2884 }
2885
2886 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2887}
2888
2889static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2890 int fd, r;
2891 struct statfs s;
8c6db833
LP
2892
2893 assert(path);
2894
f56d5db9
LP
2895 /* We refuse to clean the root file system with this
2896 * call. This is extra paranoia to never cause a really
2897 * seriously broken system. */
2898 if (path_equal(path, "/")) {
2899 log_error("Attempted to remove entire root file system, and we can't allow that.");
2900 return -EPERM;
2901 }
461b1822 2902
d4d046e3
LP
2903 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2904 if (fd < 0) {
8c6db833
LP
2905
2906 if (errno != ENOTDIR)
2907 return -errno;
2908
f56d5db9
LP
2909 if (!dangerous) {
2910 if (statfs(path, &s) < 0)
2911 return -errno;
2912
943aad8c 2913 if (!is_temporary_fs(&s)) {
f56d5db9
LP
2914 log_error("Attempted to remove disk file system, and we can't allow that.");
2915 return -EPERM;
2916 }
2917 }
2918
8c6db833 2919 if (delete_root && !only_dirs)
d4d046e3 2920 if (unlink(path) < 0 && errno != ENOENT)
8c6db833
LP
2921 return -errno;
2922
2923 return 0;
2924 }
2925
f56d5db9
LP
2926 if (!dangerous) {
2927 if (fstatfs(fd, &s) < 0) {
03e334a1 2928 safe_close(fd);
f56d5db9
LP
2929 return -errno;
2930 }
ad293f5a 2931
943aad8c 2932 if (!is_temporary_fs(&s)) {
f56d5db9 2933 log_error("Attempted to remove disk file system, and we can't allow that.");
03e334a1 2934 safe_close(fd);
f56d5db9
LP
2935 return -EPERM;
2936 }
2937 }
2938
2939 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
ad293f5a
LP
2940 if (delete_root) {
2941
8d53b453 2942 if (honour_sticky && file_is_priv_sticky(path) > 0)
ad293f5a 2943 return r;
8c6db833 2944
e27796a0 2945 if (rmdir(path) < 0 && errno != ENOENT) {
8c6db833
LP
2946 if (r == 0)
2947 r = -errno;
2948 }
ad293f5a 2949 }
8c6db833
LP
2950
2951 return r;
2952}
2953
f56d5db9
LP
2954int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2955 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2956}
2957
2958int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2959 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2960}
2961
8c6db833
LP
2962int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2963 assert(path);
2964
2965 /* Under the assumption that we are running privileged we
2966 * first change the access mode and only then hand out
2967 * ownership to avoid a window where access is too open. */
2968
8d53b453
LP
2969 if (mode != (mode_t) -1)
2970 if (chmod(path, mode) < 0)
2971 return -errno;
8c6db833 2972
8d53b453
LP
2973 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2974 if (chown(path, uid, gid) < 0)
2975 return -errno;
8c6db833
LP
2976
2977 return 0;
ef2f1067
LP
2978}
2979
f4b47811
LP
2980int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2981 assert(fd >= 0);
2982
2983 /* Under the assumption that we are running privileged we
2984 * first change the access mode and only then hand out
2985 * ownership to avoid a window where access is too open. */
2986
9588bc32
LP
2987 if (mode != (mode_t) -1)
2988 if (fchmod(fd, mode) < 0)
2989 return -errno;
f4b47811 2990
9588bc32
LP
2991 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2992 if (fchown(fd, uid, gid) < 0)
2993 return -errno;
f4b47811
LP
2994
2995 return 0;
2996}
2997
82c121a4
LP
2998cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2999 cpu_set_t *r;
3000 unsigned n = 1024;
3001
3002 /* Allocates the cpuset in the right size */
3003
3004 for (;;) {
3005 if (!(r = CPU_ALLOC(n)))
3006 return NULL;
3007
3008 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3009 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3010
3011 if (ncpus)
3012 *ncpus = n;
3013
3014 return r;
3015 }
3016
3017 CPU_FREE(r);
3018
3019 if (errno != EINVAL)
3020 return NULL;
3021
3022 n *= 2;
3023 }
3024}
3025
984a2be4 3026int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
9ab7a8d2 3027 static const char status_indent[] = " "; /* "[" STATUS "] " */
669bec5d
LP
3028 _cleanup_free_ char *s = NULL;
3029 _cleanup_close_ int fd = -1;
b92bea5d 3030 struct iovec iovec[6] = {};
81beb750 3031 int n = 0;
984a2be4 3032 static bool prev_ephemeral;
9e58ff9c
LP
3033
3034 assert(format);
3035
9ab7a8d2 3036 /* This is independent of logging, as status messages are
9e58ff9c
LP
3037 * optional and go exclusively to the console. */
3038
3039 if (vasprintf(&s, format, ap) < 0)
669bec5d 3040 return log_oom();
9e58ff9c 3041
67e5cc4f 3042 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
81beb750 3043 if (fd < 0)
669bec5d 3044 return fd;
9e58ff9c 3045
67e5cc4f 3046 if (ellipse) {
9ab7a8d2
MS
3047 char *e;
3048 size_t emax, sl;
3049 int c;
3050
67e5cc4f
LP
3051 c = fd_columns(fd);
3052 if (c <= 0)
3053 c = 80;
81beb750 3054
669bec5d 3055 sl = status ? sizeof(status_indent)-1 : 0;
9ab7a8d2
MS
3056
3057 emax = c - sl - 1;
3058 if (emax < 3)
3059 emax = 3;
81beb750 3060
58d61742 3061 e = ellipsize(s, emax, 50);
67e5cc4f
LP
3062 if (e) {
3063 free(s);
3064 s = e;
3065 }
81beb750
LP
3066 }
3067
984a2be4
MS
3068 if (prev_ephemeral)
3069 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
3070 prev_ephemeral = ephemeral;
3071
9ab7a8d2
MS
3072 if (status) {
3073 if (!isempty(status)) {
3074 IOVEC_SET_STRING(iovec[n++], "[");
3075 IOVEC_SET_STRING(iovec[n++], status);
3076 IOVEC_SET_STRING(iovec[n++], "] ");
3077 } else
3078 IOVEC_SET_STRING(iovec[n++], status_indent);
81beb750
LP
3079 }
3080
9ab7a8d2 3081 IOVEC_SET_STRING(iovec[n++], s);
984a2be4
MS
3082 if (!ephemeral)
3083 IOVEC_SET_STRING(iovec[n++], "\n");
81beb750 3084
669bec5d
LP
3085 if (writev(fd, iovec, n) < 0)
3086 return -errno;
9e58ff9c 3087
669bec5d 3088 return 0;
9e58ff9c
LP
3089}
3090
984a2be4 3091int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
c846ff47 3092 va_list ap;
669bec5d 3093 int r;
c846ff47
LP
3094
3095 assert(format);
3096
3097 va_start(ap, format);
984a2be4 3098 r = status_vprintf(status, ellipse, ephemeral, format, ap);
c846ff47 3099 va_end(ap);
669bec5d
LP
3100
3101 return r;
c846ff47
LP
3102}
3103
fab56fc5
LP
3104char *replace_env(const char *format, char **env) {
3105 enum {
3106 WORD,
c24eb49e 3107 CURLY,
fab56fc5
LP
3108 VARIABLE
3109 } state = WORD;
3110
3111 const char *e, *word = format;
3112 char *r = NULL, *k;
3113
3114 assert(format);
3115
3116 for (e = format; *e; e ++) {
3117
3118 switch (state) {
3119
3120 case WORD:
3121 if (*e == '$')
c24eb49e 3122 state = CURLY;
fab56fc5
LP
3123 break;
3124
c24eb49e
LP
3125 case CURLY:
3126 if (*e == '{') {
fab56fc5
LP
3127 if (!(k = strnappend(r, word, e-word-1)))
3128 goto fail;
3129
3130 free(r);
3131 r = k;
3132
3133 word = e-1;
3134 state = VARIABLE;
3135
3136 } else if (*e == '$') {
3137 if (!(k = strnappend(r, word, e-word)))
3138 goto fail;
3139
3140 free(r);
3141 r = k;
3142
3143 word = e+1;
3144 state = WORD;
3145 } else
3146 state = WORD;
3147 break;
3148
3149 case VARIABLE:
c24eb49e 3150 if (*e == '}') {
b95cf362 3151 const char *t;
fab56fc5 3152
4d1a6904 3153 t = strempty(strv_env_get_n(env, word+2, e-word-2));
fab56fc5 3154
4d1a6904
LP
3155 k = strappend(r, t);
3156 if (!k)
b95cf362 3157 goto fail;
fab56fc5 3158
b95cf362
LP
3159 free(r);
3160 r = k;
fab56fc5 3161
b95cf362 3162 word = e+1;
fab56fc5
LP
3163 state = WORD;
3164 }
3165 break;
3166 }
3167 }
3168
3169 if (!(k = strnappend(r, word, e-word)))
3170 goto fail;
3171
3172 free(r);
3173 return k;
3174
3175fail:
3176 free(r);
3177 return NULL;
3178}
3179
3180char **replace_env_argv(char **argv, char **env) {
b2fadec6 3181 char **ret, **i;
c24eb49e
LP
3182 unsigned k = 0, l = 0;
3183
3184 l = strv_length(argv);
fab56fc5 3185
b2fadec6
ZJS
3186 ret = new(char*, l+1);
3187 if (!ret)
fab56fc5
LP
3188 return NULL;
3189
3190 STRV_FOREACH(i, argv) {
c24eb49e
LP
3191
3192 /* If $FOO appears as single word, replace it by the split up variable */
b95cf362
LP
3193 if ((*i)[0] == '$' && (*i)[1] != '{') {
3194 char *e;
3195 char **w, **m;
3196 unsigned q;
c24eb49e 3197
4d1a6904
LP
3198 e = strv_env_get(env, *i+1);
3199 if (e) {
b2fadec6 3200 int r;
c24eb49e 3201
b2fadec6
ZJS
3202 r = strv_split_quoted(&m, e);
3203 if (r < 0) {
3204 ret[k] = NULL;
3205 strv_free(ret);
c24eb49e
LP
3206 return NULL;
3207 }
b95cf362
LP
3208 } else
3209 m = NULL;
c24eb49e 3210
b95cf362
LP
3211 q = strv_length(m);
3212 l = l + q - 1;
c24eb49e 3213
b2fadec6
ZJS
3214 w = realloc(ret, sizeof(char*) * (l+1));
3215 if (!w) {
3216 ret[k] = NULL;
3217 strv_free(ret);
b95cf362
LP
3218 strv_free(m);
3219 return NULL;
3220 }
c24eb49e 3221
b2fadec6 3222 ret = w;
b95cf362 3223 if (m) {
b2fadec6 3224 memcpy(ret + k, m, q * sizeof(char*));
c24eb49e 3225 free(m);
c24eb49e 3226 }
b95cf362
LP
3227
3228 k += q;
3229 continue;
c24eb49e
LP
3230 }
3231
3232 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
b2fadec6
ZJS
3233 ret[k] = replace_env(*i, env);
3234 if (!ret[k]) {
3235 strv_free(ret);
fab56fc5
LP
3236 return NULL;
3237 }
b2fadec6 3238 k++;
fab56fc5
LP
3239 }
3240
b2fadec6
ZJS
3241 ret[k] = NULL;
3242 return ret;
fab56fc5
LP
3243}
3244
81beb750 3245int fd_columns(int fd) {
b92bea5d 3246 struct winsize ws = {};
81beb750
LP
3247
3248 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3249 return -errno;
3250
3251 if (ws.ws_col <= 0)
3252 return -EIO;
3253
3254 return ws.ws_col;
3255}
3256
28917d7d 3257unsigned columns(void) {
fa776d8e 3258 const char *e;
7009eec2 3259 int c;
fa776d8e 3260
28917d7d
LP
3261 if (_likely_(cached_columns > 0))
3262 return cached_columns;
11f96fac 3263
28917d7d
LP
3264 c = 0;
3265 e = getenv("COLUMNS");
3266 if (e)
7009eec2 3267 safe_atoi(e, &c);
fa776d8e 3268
28917d7d
LP
3269 if (c <= 0)
3270 c = fd_columns(STDOUT_FILENO);
fa776d8e 3271
28917d7d
LP
3272 if (c <= 0)
3273 c = 80;
11f96fac 3274
28917d7d
LP
3275 cached_columns = c;
3276 return c;
11f96fac
ZJS
3277}
3278
8f2d43a0 3279int fd_lines(int fd) {
b92bea5d 3280 struct winsize ws = {};
8f2d43a0
LP
3281
3282 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3283 return -errno;
3284
3285 if (ws.ws_row <= 0)
3286 return -EIO;
3287
3288 return ws.ws_row;
3289}
3290
3291unsigned lines(void) {
8f2d43a0 3292 const char *e;
ed757c0c 3293 unsigned l;
8f2d43a0 3294
ed757c0c
LP
3295 if (_likely_(cached_lines > 0))
3296 return cached_lines;
8f2d43a0 3297
ed757c0c 3298 l = 0;
8f2d43a0
LP
3299 e = getenv("LINES");
3300 if (e)
ed757c0c 3301 safe_atou(e, &l);
8f2d43a0 3302
ed757c0c
LP
3303 if (l <= 0)
3304 l = fd_lines(STDOUT_FILENO);
8f2d43a0 3305
ed757c0c
LP
3306 if (l <= 0)
3307 l = 24;
8f2d43a0 3308
ed757c0c
LP
3309 cached_lines = l;
3310 return cached_lines;
3311}
3312
3313/* intended to be used as a SIGWINCH sighandler */
3314void columns_lines_cache_reset(int signum) {
3315 cached_columns = 0;
3316 cached_lines = 0;
3317}
3318
3319bool on_tty(void) {
3320 static int cached_on_tty = -1;
3321
3322 if (_unlikely_(cached_on_tty < 0))
3323 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3324
3325 return cached_on_tty;
8f2d43a0
LP
3326}
3327
9d9951a4
HH
3328int files_same(const char *filea, const char *fileb) {
3329 struct stat a, b;
b4f10a5e 3330
9d9951a4 3331 if (stat(filea, &a) < 0)
b4f10a5e
LP
3332 return -errno;
3333
9d9951a4 3334 if (stat(fileb, &b) < 0)
b4f10a5e
LP
3335 return -errno;
3336
9d9951a4
HH
3337 return a.st_dev == b.st_dev &&
3338 a.st_ino == b.st_ino;
3339}
3340
3341int running_in_chroot(void) {
3342 int ret;
3343
3344 ret = files_same("/proc/1/root", "/");
3345 if (ret < 0)
3346 return ret;
3347
3348 return ret == 0;
b4f10a5e
LP
3349}
3350
f405e86d 3351static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
72f59706 3352 size_t x;
8fe914ec
LP
3353 char *r;
3354
3355 assert(s);
3356 assert(percent <= 100);
72f59706 3357 assert(new_length >= 3);
8fe914ec 3358
72f59706
LP
3359 if (old_length <= 3 || old_length <= new_length)
3360 return strndup(s, old_length);
8fe914ec 3361
72f59706
LP
3362 r = new0(char, new_length+1);
3363 if (!r)
a6f0104a 3364 return NULL;
8fe914ec 3365
72f59706 3366 x = (new_length * percent) / 100;
8fe914ec 3367
72f59706
LP
3368 if (x > new_length - 3)
3369 x = new_length - 3;
8fe914ec
LP
3370
3371 memcpy(r, s, x);
3372 r[x] = '.';
3373 r[x+1] = '.';
3374 r[x+2] = '.';
3375 memcpy(r + x + 3,
72f59706
LP
3376 s + old_length - (new_length - x - 3),
3377 new_length - x - 3);
8fe914ec
LP
3378
3379 return r;
3380}
3381
f405e86d
SL
3382char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3383 size_t x;
3384 char *e;
3385 const char *i, *j;
3386 unsigned k, len, len2;
3387
3388 assert(s);
3389 assert(percent <= 100);
3390 assert(new_length >= 3);
3391
3392 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3393 if (ascii_is_valid(s))
3394 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3395
3396 if (old_length <= 3 || old_length <= new_length)
3397 return strndup(s, old_length);
3398
3399 x = (new_length * percent) / 100;
3400
3401 if (x > new_length - 3)
3402 x = new_length - 3;
3403
3404 k = 0;
3405 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3406 int c;
3407
3408 c = utf8_encoded_to_unichar(i);
3409 if (c < 0)
3410 return NULL;
3411 k += unichar_iswide(c) ? 2 : 1;
3412 }
3413
3414 if (k > x) /* last character was wide and went over quota */
3415 x ++;
3416
3417 for (j = s + old_length; k < new_length && j > i; ) {
3418 int c;
3419
3420 j = utf8_prev_char(j);
3421 c = utf8_encoded_to_unichar(j);
3422 if (c < 0)
3423 return NULL;
3424 k += unichar_iswide(c) ? 2 : 1;
3425 }
3426 assert(i <= j);
3427
3428 /* we don't actually need to ellipsize */
3429 if (i == j)
3430 return memdup(s, old_length + 1);
3431
3432 /* make space for ellipsis */
3433 j = utf8_next_char(j);
3434
3435 len = i - s;
3436 len2 = s + old_length - j;
3437 e = new(char, len + 3 + len2 + 1);
3438 if (!e)
3439 return NULL;
3440
3441 /*
3442 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3443 old_length, new_length, x, len, len2, k);
3444 */
3445
3446 memcpy(e, s, len);
3447 e[len] = 0xe2; /* tri-dot ellipsis: … */
3448 e[len + 1] = 0x80;
3449 e[len + 2] = 0xa6;
3450
3451 memcpy(e + len + 3, j, len2 + 1);
3452
3453 return e;
3454}
3455
72f59706
LP
3456char *ellipsize(const char *s, size_t length, unsigned percent) {
3457 return ellipsize_mem(s, strlen(s), length, percent);
3458}
3459
c38dfac9 3460int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
03e334a1 3461 _cleanup_close_ int fd;
c38dfac9 3462 int r;
f6144808
LP
3463
3464 assert(path);
3465
c38dfac9
KS
3466 if (parents)
3467 mkdir_parents(path, 0755);
73836c5c 3468
c38dfac9 3469 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
73836c5c 3470 if (fd < 0)
f6144808
LP
3471 return -errno;
3472
c38dfac9
KS
3473 if (mode > 0) {
3474 r = fchmod(fd, mode);
3475 if (r < 0)
3476 return -errno;
3477 }
3478
359efc59 3479 if (uid != (uid_t) -1 || gid != (gid_t) -1) {
c38dfac9
KS
3480 r = fchown(fd, uid, gid);
3481 if (r < 0)
3482 return -errno;
3483 }
3484
3a43da28 3485 if (stamp != USEC_INFINITY) {
c38dfac9
KS
3486 struct timespec ts[2];
3487
3488 timespec_store(&ts[0], stamp);
359efc59 3489 ts[1] = ts[0];
c38dfac9
KS
3490 r = futimens(fd, ts);
3491 } else
3492 r = futimens(fd, NULL);
3493 if (r < 0)
3494 return -errno;
3495
f6144808
LP
3496 return 0;
3497}
afea26ad 3498
c38dfac9 3499int touch(const char *path) {
3a43da28 3500 return touch_file(path, false, USEC_INFINITY, (uid_t) -1, (gid_t) -1, 0);
c38dfac9
KS
3501}
3502
97c4a07d 3503char *unquote(const char *s, const char* quotes) {
11ce3427
LP
3504 size_t l;
3505 assert(s);
3506
73836c5c
LP
3507 /* This is rather stupid, simply removes the heading and
3508 * trailing quotes if there is one. Doesn't care about
57f30678
LP
3509 * escaping or anything. We should make this smarter one
3510 * day...*/
73836c5c 3511
31ed59c5
LP
3512 l = strlen(s);
3513 if (l < 2)
11ce3427
LP
3514 return strdup(s);
3515
97c4a07d 3516 if (strchr(quotes, s[0]) && s[l-1] == s[0])
11ce3427
LP
3517 return strndup(s+1, l-2);
3518
3519 return strdup(s);
3520}
3521
5f7c426e 3522char *normalize_env_assignment(const char *s) {
57f30678
LP
3523 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3524 char *eq, *r;
5f7c426e 3525
57f30678
LP
3526 eq = strchr(s, '=');
3527 if (!eq) {
3528 char *t;
5f7c426e 3529
57f30678
LP
3530 r = strdup(s);
3531 if (!r)
5f7c426e
LP
3532 return NULL;
3533
57f30678
LP
3534 t = strstrip(r);
3535 if (t == r)
3536 return r;
3537
3538 memmove(r, t, strlen(t) + 1);
3539 return r;
5f7c426e
LP
3540 }
3541
57f30678
LP
3542 name = strndup(s, eq - s);
3543 if (!name)
5f7c426e
LP
3544 return NULL;
3545
57f30678
LP
3546 p = strdup(eq + 1);
3547 if (!p)
5f7c426e 3548 return NULL;
5f7c426e
LP
3549
3550 value = unquote(strstrip(p), QUOTES);
57f30678 3551 if (!value)
5f7c426e 3552 return NULL;
5f7c426e 3553
57f30678 3554 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
5f7c426e
LP
3555 r = NULL;
3556
5f7c426e
LP
3557 return r;
3558}
3559
8e12a6ae 3560int wait_for_terminate(pid_t pid, siginfo_t *status) {
1968a360
LP
3561 siginfo_t dummy;
3562
2e78aa99 3563 assert(pid >= 1);
1968a360
LP
3564
3565 if (!status)
3566 status = &dummy;
2e78aa99
LP
3567
3568 for (;;) {
8e12a6ae
LP
3569 zero(*status);
3570
3571 if (waitid(P_PID, pid, status, WEXITED) < 0) {
2e78aa99
LP
3572
3573 if (errno == EINTR)
3574 continue;
3575
3576 return -errno;
3577 }
3578
3579 return 0;
3580 }
3581}
3582
0659e8ba
LS
3583/*
3584 * Return values:
3585 * < 0 : wait_for_terminate() failed to get the state of the
3586 * process, the process was terminated by a signal, or
3587 * failed for an unknown reason.
3588 * >=0 : The process terminated normally, and its exit code is
3589 * returned.
3590 *
3591 * That is, success is indicated by a return value of zero, and an
3592 * error is indicated by a non-zero value.
3593 */
97c4a07d
LP
3594int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3595 int r;
3596 siginfo_t status;
3597
3598 assert(name);
3599 assert(pid > 1);
3600
d87be9b0
LP
3601 r = wait_for_terminate(pid, &status);
3602 if (r < 0) {
97c4a07d
LP
3603 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3604 return r;
3605 }
3606
3607 if (status.si_code == CLD_EXITED) {
3608 if (status.si_status != 0) {
3609 log_warning("%s failed with error code %i.", name, status.si_status);
0a27cf3f 3610 return status.si_status;
97c4a07d
LP
3611 }
3612
3613 log_debug("%s succeeded.", name);
3614 return 0;
3615
3616 } else if (status.si_code == CLD_KILLED ||
3617 status.si_code == CLD_DUMPED) {
3618
3619 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3620 return -EPROTO;
3621 }
3622
3623 log_warning("%s failed due to unknown reason.", name);
3624 return -EPROTO;
97c4a07d
LP
3625}
3626
919ce0b7 3627noreturn void freeze(void) {
720ce21d
LP
3628
3629 /* Make sure nobody waits for us on a socket anymore */
3630 close_all_fds(NULL, 0);
3631
c29597a1
LP
3632 sync();
3633
3c14d26c
LP
3634 for (;;)
3635 pause();
3636}
3637
00dc5d76
LP
3638bool null_or_empty(struct stat *st) {
3639 assert(st);
3640
3641 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3642 return true;
3643
c8f26f42 3644 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
00dc5d76
LP
3645 return true;
3646
3647 return false;
3648}
3649
83096483
LP
3650int null_or_empty_path(const char *fn) {
3651 struct stat st;
3652
3653 assert(fn);
3654
3655 if (stat(fn, &st) < 0)
3656 return -errno;
3657
3658 return null_or_empty(&st);
3659}
3660
ed88bcfb
ZJS
3661int null_or_empty_fd(int fd) {
3662 struct stat st;
3663
3664 assert(fd >= 0);
3665
3666 if (fstat(fd, &st) < 0)
3667 return -errno;
3668
3669 return null_or_empty(&st);
3670}
3671
a247755d 3672DIR *xopendirat(int fd, const char *name, int flags) {
c4731d11
LP
3673 int nfd;
3674 DIR *d;
3675
dd94c17e
LP
3676 assert(!(flags & O_CREAT));
3677
3678 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
73836c5c 3679 if (nfd < 0)
c4731d11
LP
3680 return NULL;
3681
73836c5c
LP
3682 d = fdopendir(nfd);
3683 if (!d) {
03e334a1 3684 safe_close(nfd);
c4731d11
LP
3685 return NULL;
3686 }
3687
3688 return d;
3b63d2d3
LP
3689}
3690
8a0867d6
LP
3691int signal_from_string_try_harder(const char *s) {
3692 int signo;
3693 assert(s);
3694
73836c5c
LP
3695 signo = signal_from_string(s);
3696 if (signo <= 0)
8a0867d6
LP
3697 if (startswith(s, "SIG"))
3698 return signal_from_string(s+3);
3699
3700 return signo;
3701}
3702
383182b5 3703static char *tag_to_udev_node(const char *tagvalue, const char *by) {
22f5f628 3704 _cleanup_free_ char *t = NULL, *u = NULL;
22f5f628 3705 size_t enc_len;
e23a0ce8 3706
383182b5 3707 u = unquote(tagvalue, "\"\'");
6db615c1 3708 if (!u)
383182b5 3709 return NULL;
e23a0ce8 3710
1d5989fd 3711 enc_len = strlen(u) * 4 + 1;
22f5f628 3712 t = new(char, enc_len);
6db615c1 3713 if (!t)
383182b5 3714 return NULL;
e23a0ce8 3715
8f6ce71f 3716 if (encode_devnode_name(u, t, enc_len) < 0)
22f5f628 3717 return NULL;
e23a0ce8 3718
6db615c1 3719 return strjoin("/dev/disk/by-", by, "/", t, NULL);
383182b5 3720}
e23a0ce8 3721
383182b5 3722char *fstab_node_to_udev_node(const char *p) {
faa368e3
LP
3723 assert(p);
3724
383182b5
DR
3725 if (startswith(p, "LABEL="))
3726 return tag_to_udev_node(p+6, "label");
e23a0ce8 3727
383182b5
DR
3728 if (startswith(p, "UUID="))
3729 return tag_to_udev_node(p+5, "uuid");
e23a0ce8 3730
84cc2abf
DR
3731 if (startswith(p, "PARTUUID="))
3732 return tag_to_udev_node(p+9, "partuuid");
3733
3734 if (startswith(p, "PARTLABEL="))
3735 return tag_to_udev_node(p+10, "partlabel");
3736
e23a0ce8
LP
3737 return strdup(p);
3738}
3739
f212ac12
LP
3740bool tty_is_vc(const char *tty) {
3741 assert(tty);
3742
98a28fef
LP
3743 return vtnr_from_tty(tty) >= 0;
3744}
3745
d1122ad5
LP
3746bool tty_is_console(const char *tty) {
3747 assert(tty);
3748
3749 if (startswith(tty, "/dev/"))
3750 tty += 5;
3751
3752 return streq(tty, "console");
3753}
3754
98a28fef
LP
3755int vtnr_from_tty(const char *tty) {
3756 int i, r;
3757
3758 assert(tty);
3759
3760 if (startswith(tty, "/dev/"))
3761 tty += 5;
3762
3763 if (!startswith(tty, "tty") )
3764 return -EINVAL;
3765
3766 if (tty[3] < '0' || tty[3] > '9')
3767 return -EINVAL;
3768
3769 r = safe_atoi(tty+3, &i);
3770 if (r < 0)
3771 return r;
3772
3773 if (i < 0 || i > 63)
3774 return -EINVAL;
3775
3776 return i;
f212ac12
LP
3777}
3778
21baf21a
MS
3779char *resolve_dev_console(char **active) {
3780 char *tty;
3781
3782 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3783 * (i.e. not read-only-mounted which is a sign for container setups) */
3784
3785 if (path_is_read_only_fs("/sys") > 0)
3786 return NULL;
3787
3788 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3789 return NULL;
3790
3791 /* If multiple log outputs are configured the last one is what
3792 * /dev/console points to */
3793 tty = strrchr(*active, ' ');
3794 if (tty)
3795 tty++;
3796 else
3797 tty = *active;
3798
8aa5429a
OB
3799 if (streq(tty, "tty0")) {
3800 char *tmp;
3801
3802 /* Get the active VC (e.g. tty1) */
3803 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
3804 free(*active);
3805 tty = *active = tmp;
3806 }
3807 }
3808
21baf21a
MS
3809 return tty;
3810}
3811
3043935f 3812bool tty_is_vc_resolve(const char *tty) {
9588bc32 3813 _cleanup_free_ char *active = NULL;
3030ccd7 3814
e3aa71c3
LP
3815 assert(tty);
3816
3817 if (startswith(tty, "/dev/"))
3818 tty += 5;
3819
21baf21a
MS
3820 if (streq(tty, "console")) {
3821 tty = resolve_dev_console(&active);
3822 if (!tty)
3823 return false;
3824 }
3030ccd7 3825
9588bc32 3826 return tty_is_vc(tty);
3043935f
LP
3827}
3828
3829const char *default_term_for_tty(const char *tty) {
3830 assert(tty);
3831
acda6a05 3832 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
e3aa71c3
LP
3833}
3834
87d2c1ff 3835bool dirent_is_file(const struct dirent *de) {
fb19a739
LP
3836 assert(de);
3837
3838 if (ignore_file(de->d_name))
3839 return false;
3840
3841 if (de->d_type != DT_REG &&
3842 de->d_type != DT_LNK &&
3843 de->d_type != DT_UNKNOWN)
3844 return false;
3845
3846 return true;
3847}
3848
87d2c1ff
LP
3849bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3850 assert(de);
3851
a228a22f
LP
3852 if (de->d_type != DT_REG &&
3853 de->d_type != DT_LNK &&
3854 de->d_type != DT_UNKNOWN)
3855 return false;
3856
3857 if (ignore_file_allow_backup(de->d_name))
87d2c1ff
LP
3858 return false;
3859
3860 return endswith(de->d_name, suffix);
3861}
3862
e2680723 3863void execute_directory(const char *directory, DIR *d, usec_t timeout, char *argv[]) {
aa62a893
LP
3864 pid_t executor_pid;
3865 int r;
83cc030f
LP
3866
3867 assert(directory);
3868
aa62a893
LP
3869 /* Executes all binaries in a directory in parallel and waits
3870 * for them to finish. Optionally a timeout is applied. */
83cc030f 3871
aa62a893
LP
3872 executor_pid = fork();
3873 if (executor_pid < 0) {
3874 log_error("Failed to fork: %m");
3875 return;
83cc030f 3876
aa62a893
LP
3877 } else if (executor_pid == 0) {
3878 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
3879 _cleanup_closedir_ DIR *_d = NULL;
3880 struct dirent *de;
3881 sigset_t ss;
83cc030f 3882
aa62a893
LP
3883 /* We fork this all off from a child process so that
3884 * we can somewhat cleanly make use of SIGALRM to set
3885 * a time limit */
83cc030f 3886
aa62a893 3887 reset_all_signal_handlers();
83cc030f 3888
aa62a893
LP
3889 assert_se(sigemptyset(&ss) == 0);
3890 assert_se(sigprocmask(SIG_SETMASK, &ss, NULL) == 0);
83cc030f 3891
aa62a893 3892 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
83cc030f 3893
aa62a893
LP
3894 if (!d) {
3895 d = _d = opendir(directory);
3896 if (!d) {
3897 if (errno == ENOENT)
3898 _exit(EXIT_SUCCESS);
83cc030f 3899
aa62a893
LP
3900 log_error("Failed to enumerate directory %s: %m", directory);
3901 _exit(EXIT_FAILURE);
3902 }
83cc030f
LP
3903 }
3904
aa62a893
LP
3905 pids = hashmap_new(NULL, NULL);
3906 if (!pids) {
3907 log_oom();
3908 _exit(EXIT_FAILURE);
83cc030f
LP
3909 }
3910
aa62a893
LP
3911 FOREACH_DIRENT(de, d, break) {
3912 _cleanup_free_ char *path = NULL;
3913 pid_t pid;
83cc030f 3914
aa62a893
LP
3915 if (!dirent_is_file(de))
3916 continue;
83cc030f 3917
418b9be5
LP
3918 path = strjoin(directory, "/", de->d_name, NULL);
3919 if (!path) {
aa62a893
LP
3920 log_oom();
3921 _exit(EXIT_FAILURE);
3922 }
83cc030f 3923
aa62a893
LP
3924 pid = fork();
3925 if (pid < 0) {
3926 log_error("Failed to fork: %m");
3927 continue;
3928 } else if (pid == 0) {
3929 char *_argv[2];
83cc030f 3930
aa62a893 3931 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
83cc030f 3932
aa62a893
LP
3933 if (!argv) {
3934 _argv[0] = path;
3935 _argv[1] = NULL;
3936 argv = _argv;
3937 } else
3938 argv[0] = path;
83cc030f 3939
aa62a893
LP
3940 execv(path, argv);
3941 log_error("Failed to execute %s: %m", path);
3942 _exit(EXIT_FAILURE);
3943 }
83cc030f 3944
83cc030f 3945
aa62a893 3946 log_debug("Spawned %s as " PID_FMT ".", path, pid);
83cc030f 3947
aa62a893
LP
3948 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
3949 if (r < 0) {
3950 log_oom();
3951 _exit(EXIT_FAILURE);
3952 }
3953
3954 path = NULL;
83cc030f
LP
3955 }
3956
aa62a893
LP
3957 /* Abort execution of this process after the
3958 * timout. We simply rely on SIGALRM as default action
3959 * terminating the process, and turn on alarm(). */
3960
3a43da28 3961 if (timeout != USEC_INFINITY)
aa62a893
LP
3962 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
3963
3964 while (!hashmap_isempty(pids)) {
3965 _cleanup_free_ char *path = NULL;
3966 pid_t pid;
3967
3968 pid = PTR_TO_UINT(hashmap_first_key(pids));
3969 assert(pid > 0);
83cc030f 3970
aa62a893
LP
3971 path = hashmap_remove(pids, UINT_TO_PTR(pid));
3972 assert(path);
3973
3974 wait_for_terminate_and_warn(path, pid);
83cc030f 3975 }
83cc030f 3976
aa62a893
LP
3977 _exit(EXIT_SUCCESS);
3978 }
83cc030f 3979
aa62a893 3980 wait_for_terminate_and_warn(directory, executor_pid);
83cc030f
LP
3981}
3982
430c18ed
LP
3983int kill_and_sigcont(pid_t pid, int sig) {
3984 int r;
3985
3986 r = kill(pid, sig) < 0 ? -errno : 0;
3987
3988 if (r >= 0)
3989 kill(pid, SIGCONT);
3990
3991 return r;
3992}
3993
05feefe0
LP
3994bool nulstr_contains(const char*nulstr, const char *needle) {
3995 const char *i;
3996
3997 if (!nulstr)
3998 return false;
3999
4000 NULSTR_FOREACH(i, nulstr)
4001 if (streq(i, needle))
4002 return true;
4003
4004 return false;
4005}
4006
6faa1114 4007bool plymouth_running(void) {
9408a2d2 4008 return access("/run/plymouth/pid", F_OK) >= 0;
6faa1114
LP
4009}
4010
9beb3f4d
LP
4011char* strshorten(char *s, size_t l) {
4012 assert(s);
4013
4014 if (l < strlen(s))
4015 s[l] = 0;
4016
4017 return s;
4018}
4019
4020static bool hostname_valid_char(char c) {
4021 return
4022 (c >= 'a' && c <= 'z') ||
4023 (c >= 'A' && c <= 'Z') ||
4024 (c >= '0' && c <= '9') ||
4025 c == '-' ||
4026 c == '_' ||
4027 c == '.';
4028}
4029
4030bool hostname_is_valid(const char *s) {
4031 const char *p;
aa3c5cf8 4032 bool dot;
9beb3f4d
LP
4033
4034 if (isempty(s))
4035 return false;
4036
aa3c5cf8
LP
4037 for (p = s, dot = true; *p; p++) {
4038 if (*p == '.') {
4039 if (dot)
4040 return false;
4041
4042 dot = true;
4043 } else {
4044 if (!hostname_valid_char(*p))
4045 return false;
4046
4047 dot = false;
4048 }
4049 }
4050
4051 if (dot)
4052 return false;
9beb3f4d
LP
4053
4054 if (p-s > HOST_NAME_MAX)
4055 return false;
4056
4057 return true;
4058}
4059
e724b063 4060char* hostname_cleanup(char *s, bool lowercase) {
9beb3f4d 4061 char *p, *d;
cec4ead9
LP
4062 bool dot;
4063
4064 for (p = s, d = s, dot = true; *p; p++) {
4065 if (*p == '.') {
e724b063 4066 if (dot)
cec4ead9 4067 continue;
9beb3f4d 4068
e724b063 4069 *(d++) = '.';
cec4ead9 4070 dot = true;
e724b063
LP
4071 } else if (hostname_valid_char(*p)) {
4072 *(d++) = lowercase ? tolower(*p) : *p;
cec4ead9 4073 dot = false;
e724b063 4074 }
cec4ead9 4075
cec4ead9 4076 }
9beb3f4d 4077
e724b063
LP
4078 if (dot && d > s)
4079 d[-1] = 0;
4080 else
4081 *d = 0;
4082
9beb3f4d 4083 strshorten(s, HOST_NAME_MAX);
cec4ead9 4084
9beb3f4d
LP
4085 return s;
4086}
4087
7f0d207d
LP
4088bool machine_name_is_valid(const char *s) {
4089
4090 if (!hostname_is_valid(s))
4091 return false;
4092
4093 /* Machine names should be useful hostnames, but also be
4094 * useful in unit names, hence we enforce a stricter length
4095 * limitation. */
4096
4097 if (strlen(s) > 64)
4098 return false;
4099
4100 return true;
4101}
4102
1325aa42 4103int pipe_eof(int fd) {
b92bea5d
ZJS
4104 struct pollfd pollfd = {
4105 .fd = fd,
4106 .events = POLLIN|POLLHUP,
4107 };
1325aa42 4108
d37a91e8
LP
4109 int r;
4110
1325aa42
LP
4111 r = poll(&pollfd, 1, 0);
4112 if (r < 0)
4113 return -errno;
4114
4115 if (r == 0)
4116 return 0;
4117
4118 return pollfd.revents & POLLHUP;
4119}
4120
8f2d43a0 4121int fd_wait_for_event(int fd, int event, usec_t t) {
968d3d24 4122
b92bea5d
ZJS
4123 struct pollfd pollfd = {
4124 .fd = fd,
4125 .events = event,
4126 };
df50185b 4127
968d3d24
LP
4128 struct timespec ts;
4129 int r;
4130
3a43da28 4131 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
df50185b
LP
4132 if (r < 0)
4133 return -errno;
4134
4135 if (r == 0)
4136 return 0;
4137
4138 return pollfd.revents;
4139}
4140
5a3ab509
LP
4141int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4142 FILE *f;
4143 char *t;
5a3ab509
LP
4144 int fd;
4145
4146 assert(path);
4147 assert(_f);
4148 assert(_temp_path);
4149
2e78fa79 4150 t = tempfn_xxxxxx(path);
5a3ab509
LP
4151 if (!t)
4152 return -ENOMEM;
4153
2d5bdf5b 4154 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
5a3ab509
LP
4155 if (fd < 0) {
4156 free(t);
4157 return -errno;
4158 }
4159
4160 f = fdopen(fd, "we");
4161 if (!f) {
4162 unlink(t);
4163 free(t);
4164 return -errno;
4165 }
4166
4167 *_f = f;
4168 *_temp_path = t;
4169
4170 return 0;
4171}
4172
6ea832a2 4173int terminal_vhangup_fd(int fd) {
5a3ab509
LP
4174 assert(fd >= 0);
4175
6ea832a2
LP
4176 if (ioctl(fd, TIOCVHANGUP) < 0)
4177 return -errno;
4178
4179 return 0;
4180}
4181
4182int terminal_vhangup(const char *name) {
03e334a1 4183 _cleanup_close_ int fd;
6ea832a2
LP
4184
4185 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4186 if (fd < 0)
4187 return fd;
4188
03e334a1 4189 return terminal_vhangup_fd(fd);
6ea832a2
LP
4190}
4191
4192int vt_disallocate(const char *name) {
4193 int fd, r;
4194 unsigned u;
6ea832a2
LP
4195
4196 /* Deallocate the VT if possible. If not possible
4197 * (i.e. because it is the active one), at least clear it
4198 * entirely (including the scrollback buffer) */
4199
b83bc4e9
LP
4200 if (!startswith(name, "/dev/"))
4201 return -EINVAL;
4202
4203 if (!tty_is_vc(name)) {
4204 /* So this is not a VT. I guess we cannot deallocate
4205 * it then. But let's at least clear the screen */
4206
4207 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4208 if (fd < 0)
4209 return fd;
4210
8585357a
LP
4211 loop_write(fd,
4212 "\033[r" /* clear scrolling region */
4213 "\033[H" /* move home */
4214 "\033[2J", /* clear screen */
4215 10, false);
03e334a1 4216 safe_close(fd);
b83bc4e9
LP
4217
4218 return 0;
4219 }
6ea832a2
LP
4220
4221 if (!startswith(name, "/dev/tty"))
4222 return -EINVAL;
4223
4224 r = safe_atou(name+8, &u);
4225 if (r < 0)
4226 return r;
4227
4228 if (u <= 0)
b83bc4e9 4229 return -EINVAL;
6ea832a2 4230
b83bc4e9 4231 /* Try to deallocate */
6ea832a2
LP
4232 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4233 if (fd < 0)
4234 return fd;
4235
4236 r = ioctl(fd, VT_DISALLOCATE, u);
03e334a1 4237 safe_close(fd);
6ea832a2 4238
b83bc4e9
LP
4239 if (r >= 0)
4240 return 0;
6ea832a2 4241
b83bc4e9 4242 if (errno != EBUSY)
6ea832a2 4243 return -errno;
6ea832a2 4244
b83bc4e9
LP
4245 /* Couldn't deallocate, so let's clear it fully with
4246 * scrollback */
4247 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
6ea832a2 4248 if (fd < 0)
b83bc4e9 4249 return fd;
6ea832a2 4250
8585357a
LP
4251 loop_write(fd,
4252 "\033[r" /* clear scrolling region */
4253 "\033[H" /* move home */
4254 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4255 10, false);
03e334a1 4256 safe_close(fd);
6ea832a2 4257
b83bc4e9 4258 return 0;
6ea832a2
LP
4259}
4260
424a19f8 4261int symlink_atomic(const char *from, const char *to) {
2e78fa79 4262 _cleanup_free_ char *t = NULL;
34ca941c
LP
4263
4264 assert(from);
4265 assert(to);
4266
2e78fa79 4267 t = tempfn_random(to);
34ca941c
LP
4268 if (!t)
4269 return -ENOMEM;
4270
424a19f8
LP
4271 if (symlink(from, t) < 0)
4272 return -errno;
34ca941c
LP
4273
4274 if (rename(t, to) < 0) {
2e78fa79
LP
4275 unlink_noerrno(t);
4276 return -errno;
34ca941c
LP
4277 }
4278
424a19f8 4279 return 0;
34ca941c
LP
4280}
4281
1554afae
LP
4282int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
4283 _cleanup_free_ char *t = NULL;
4284
4285 assert(path);
4286
4287 t = tempfn_random(path);
4288 if (!t)
4289 return -ENOMEM;
4290
4291 if (mknod(t, mode, dev) < 0)
4292 return -errno;
4293
4294 if (rename(t, path) < 0) {
4295 unlink_noerrno(t);
4296 return -errno;
4297 }
4298
4299 return 0;
4300}
4301
4302int mkfifo_atomic(const char *path, mode_t mode) {
4303 _cleanup_free_ char *t = NULL;
4304
4305 assert(path);
4306
4307 t = tempfn_random(path);
4308 if (!t)
4309 return -ENOMEM;
4310
4311 if (mkfifo(t, mode) < 0)
4312 return -errno;
4313
4314 if (rename(t, path) < 0) {
4315 unlink_noerrno(t);
4316 return -errno;
4317 }
4318
4319 return 0;
4320}
4321
4d6d6518
LP
4322bool display_is_local(const char *display) {
4323 assert(display);
4324
4325 return
4326 display[0] == ':' &&
4327 display[1] >= '0' &&
4328 display[1] <= '9';
4329}
4330
4331int socket_from_display(const char *display, char **path) {
4332 size_t k;
4333 char *f, *c;
4334
4335 assert(display);
4336 assert(path);
4337
4338 if (!display_is_local(display))
4339 return -EINVAL;
4340
4341 k = strspn(display+1, "0123456789");
4342
f8294e41 4343 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
4d6d6518
LP
4344 if (!f)
4345 return -ENOMEM;
4346
4347 c = stpcpy(f, "/tmp/.X11-unix/X");
4348 memcpy(c, display+1, k);
4349 c[k] = 0;
4350
4351 *path = f;
4352
4353 return 0;
4354}
4355
d05c5031
LP
4356int get_user_creds(
4357 const char **username,
4358 uid_t *uid, gid_t *gid,
4359 const char **home,
4360 const char **shell) {
4361
1cccf435 4362 struct passwd *p;
ddd88763 4363 uid_t u;
1cccf435
MV
4364
4365 assert(username);
4366 assert(*username);
1cccf435
MV
4367
4368 /* We enforce some special rules for uid=0: in order to avoid
4369 * NSS lookups for root we hardcode its data. */
4370
4371 if (streq(*username, "root") || streq(*username, "0")) {
4372 *username = "root";
4b67834e
LP
4373
4374 if (uid)
4375 *uid = 0;
4376
4377 if (gid)
4378 *gid = 0;
4379
4380 if (home)
4381 *home = "/root";
d05c5031
LP
4382
4383 if (shell)
4384 *shell = "/bin/sh";
4385
1cccf435
MV
4386 return 0;
4387 }
4388
ddd88763 4389 if (parse_uid(*username, &u) >= 0) {
1cccf435 4390 errno = 0;
ddd88763 4391 p = getpwuid(u);
1cccf435
MV
4392
4393 /* If there are multiple users with the same id, make
4394 * sure to leave $USER to the configured value instead
4395 * of the first occurrence in the database. However if
4396 * the uid was configured by a numeric uid, then let's
4397 * pick the real username from /etc/passwd. */
4398 if (p)
4399 *username = p->pw_name;
4400 } else {
4401 errno = 0;
4402 p = getpwnam(*username);
4403 }
4404
4405 if (!p)
8333c77e 4406 return errno > 0 ? -errno : -ESRCH;
1cccf435 4407
4b67834e
LP
4408 if (uid)
4409 *uid = p->pw_uid;
4410
4411 if (gid)
4412 *gid = p->pw_gid;
4413
4414 if (home)
4415 *home = p->pw_dir;
4416
d05c5031
LP
4417 if (shell)
4418 *shell = p->pw_shell;
4419
4b67834e
LP
4420 return 0;
4421}
4422
59164be4
LP
4423char* uid_to_name(uid_t uid) {
4424 struct passwd *p;
4425 char *r;
4426
4427 if (uid == 0)
4428 return strdup("root");
4429
4430 p = getpwuid(uid);
4431 if (p)
4432 return strdup(p->pw_name);
4433
de0671ee 4434 if (asprintf(&r, UID_FMT, uid) < 0)
59164be4
LP
4435 return NULL;
4436
4437 return r;
4438}
4439
4468addc
LP
4440char* gid_to_name(gid_t gid) {
4441 struct group *p;
4442 char *r;
4443
4444 if (gid == 0)
4445 return strdup("root");
4446
4447 p = getgrgid(gid);
4448 if (p)
4449 return strdup(p->gr_name);
4450
de0671ee 4451 if (asprintf(&r, GID_FMT, gid) < 0)
4468addc
LP
4452 return NULL;
4453
4454 return r;
4455}
4456
4b67834e
LP
4457int get_group_creds(const char **groupname, gid_t *gid) {
4458 struct group *g;
4459 gid_t id;
4460
4461 assert(groupname);
4462
4463 /* We enforce some special rules for gid=0: in order to avoid
4464 * NSS lookups for root we hardcode its data. */
4465
4466 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4467 *groupname = "root";
4468
4469 if (gid)
4470 *gid = 0;
4471
4472 return 0;
4473 }
4474
4475 if (parse_gid(*groupname, &id) >= 0) {
4476 errno = 0;
4477 g = getgrgid(id);
4478
4479 if (g)
4480 *groupname = g->gr_name;
4481 } else {
4482 errno = 0;
4483 g = getgrnam(*groupname);
4484 }
4485
4486 if (!g)
8333c77e 4487 return errno > 0 ? -errno : -ESRCH;
4b67834e
LP
4488
4489 if (gid)
4490 *gid = g->gr_gid;
4491
1cccf435
MV
4492 return 0;
4493}
4494
4468addc
LP
4495int in_gid(gid_t gid) {
4496 gid_t *gids;
43673799
LP
4497 int ngroups_max, r, i;
4498
43673799
LP
4499 if (getgid() == gid)
4500 return 1;
4501
4502 if (getegid() == gid)
4503 return 1;
4504
4505 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4506 assert(ngroups_max > 0);
4507
4508 gids = alloca(sizeof(gid_t) * ngroups_max);
4509
4510 r = getgroups(ngroups_max, gids);
4511 if (r < 0)
4512 return -errno;
4513
4514 for (i = 0; i < r; i++)
4515 if (gids[i] == gid)
4516 return 1;
4517
4518 return 0;
4519}
4520
4468addc
LP
4521int in_group(const char *name) {
4522 int r;
4523 gid_t gid;
4524
4525 r = get_group_creds(&name, &gid);
4526 if (r < 0)
4527 return r;
4528
4529 return in_gid(gid);
4530}
4531
8092a428 4532int glob_exists(const char *path) {
7fd1b19b 4533 _cleanup_globfree_ glob_t g = {};
8d98da3f 4534 int k;
8092a428
LP
4535
4536 assert(path);
4537
8092a428
LP
4538 errno = 0;
4539 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4540
4541 if (k == GLOB_NOMATCH)
8d98da3f 4542 return 0;
8092a428 4543 else if (k == GLOB_NOSPACE)
8d98da3f 4544 return -ENOMEM;
8092a428 4545 else if (k == 0)
8d98da3f 4546 return !strv_isempty(g.gl_pathv);
8092a428 4547 else
8d98da3f
ZJS
4548 return errno ? -errno : -EIO;
4549}
8092a428 4550
8d98da3f
ZJS
4551int glob_extend(char ***strv, const char *path) {
4552 _cleanup_globfree_ glob_t g = {};
4553 int k;
4554 char **p;
4555
4556 errno = 0;
a8ccacf5 4557 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
8d98da3f
ZJS
4558
4559 if (k == GLOB_NOMATCH)
4560 return -ENOENT;
4561 else if (k == GLOB_NOSPACE)
4562 return -ENOMEM;
4563 else if (k != 0 || strv_isempty(g.gl_pathv))
4564 return errno ? -errno : -EIO;
4565
4566 STRV_FOREACH(p, g.gl_pathv) {
4567 k = strv_extend(strv, *p);
4568 if (k < 0)
4569 break;
4570 }
4571
4572 return k;
8092a428
LP
4573}
4574
83096483
LP
4575int dirent_ensure_type(DIR *d, struct dirent *de) {
4576 struct stat st;
4577
4578 assert(d);
4579 assert(de);
4580
4581 if (de->d_type != DT_UNKNOWN)
4582 return 0;
4583
4584 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4585 return -errno;
4586
4587 de->d_type =
4588 S_ISREG(st.st_mode) ? DT_REG :
4589 S_ISDIR(st.st_mode) ? DT_DIR :
4590 S_ISLNK(st.st_mode) ? DT_LNK :
4591 S_ISFIFO(st.st_mode) ? DT_FIFO :
4592 S_ISSOCK(st.st_mode) ? DT_SOCK :
4593 S_ISCHR(st.st_mode) ? DT_CHR :
4594 S_ISBLK(st.st_mode) ? DT_BLK :
4595 DT_UNKNOWN;
4596
4597 return 0;
4598}
4599
034a2a52 4600int get_files_in_directory(const char *path, char ***list) {
893fa014
ZJS
4601 _cleanup_closedir_ DIR *d = NULL;
4602 size_t bufsize = 0, n = 0;
4603 _cleanup_strv_free_ char **l = NULL;
034a2a52
LP
4604
4605 assert(path);
d60ef526
LP
4606
4607 /* Returns all files in a directory in *list, and the number
4608 * of files as return value. If list is NULL returns only the
893fa014 4609 * number. */
034a2a52
LP
4610
4611 d = opendir(path);
8ea913b2
LP
4612 if (!d)
4613 return -errno;
4614
034a2a52 4615 for (;;) {
7d5e9c0f 4616 struct dirent *de;
034a2a52 4617
3fd11280
FW
4618 errno = 0;
4619 de = readdir(d);
4620 if (!de && errno != 0)
4621 return -errno;
034a2a52
LP
4622 if (!de)
4623 break;
4624
4625 dirent_ensure_type(d, de);
4626
4627 if (!dirent_is_file(de))
4628 continue;
4629
d60ef526 4630 if (list) {
893fa014
ZJS
4631 /* one extra slot is needed for the terminating NULL */
4632 if (!GREEDY_REALLOC(l, bufsize, n + 2))
4633 return -ENOMEM;
034a2a52 4634
893fa014
ZJS
4635 l[n] = strdup(de->d_name);
4636 if (!l[n])
4637 return -ENOMEM;
034a2a52 4638
893fa014 4639 l[++n] = NULL;
d60ef526 4640 } else
893fa014 4641 n++;
034a2a52
LP
4642 }
4643
893fa014
ZJS
4644 if (list) {
4645 *list = l;
4646 l = NULL; /* avoid freeing */
4647 }
034a2a52 4648
893fa014 4649 return n;
034a2a52
LP
4650}
4651
b7def684 4652char *strjoin(const char *x, ...) {
911a4828
LP
4653 va_list ap;
4654 size_t l;
4655 char *r, *p;
4656
4657 va_start(ap, x);
4658
4659 if (x) {
4660 l = strlen(x);
4661
4662 for (;;) {
4663 const char *t;
040f18ea 4664 size_t n;
911a4828
LP
4665
4666 t = va_arg(ap, const char *);
4667 if (!t)
4668 break;
4669
040f18ea 4670 n = strlen(t);
e98055de
LN
4671 if (n > ((size_t) -1) - l) {
4672 va_end(ap);
040f18ea 4673 return NULL;
e98055de 4674 }
040f18ea
LP
4675
4676 l += n;
911a4828
LP
4677 }
4678 } else
4679 l = 0;
4680
4681 va_end(ap);
4682
4683 r = new(char, l+1);
4684 if (!r)
4685 return NULL;
4686
4687 if (x) {
4688 p = stpcpy(r, x);
4689
4690 va_start(ap, x);
4691
4692 for (;;) {
4693 const char *t;
4694
4695 t = va_arg(ap, const char *);
4696 if (!t)
4697 break;
4698
4699 p = stpcpy(p, t);
4700 }
8ea913b2
LP
4701
4702 va_end(ap);
911a4828
LP
4703 } else
4704 r[0] = 0;
4705
4706 return r;
4707}
4708
b636465b 4709bool is_main_thread(void) {
ec202eae 4710 static thread_local int cached = 0;
b636465b
LP
4711
4712 if (_unlikely_(cached == 0))
4713 cached = getpid() == gettid() ? 1 : -1;
4714
4715 return cached > 0;
4716}
4717
94959f0f
LP
4718int block_get_whole_disk(dev_t d, dev_t *ret) {
4719 char *p, *s;
4720 int r;
4721 unsigned n, m;
4722
4723 assert(ret);
4724
4725 /* If it has a queue this is good enough for us */
4726 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4727 return -ENOMEM;
4728
4729 r = access(p, F_OK);
4730 free(p);
4731
4732 if (r >= 0) {
4733 *ret = d;
4734 return 0;
4735 }
4736
4737 /* If it is a partition find the originating device */
4738 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4739 return -ENOMEM;
4740
4741 r = access(p, F_OK);
4742 free(p);
4743
4744 if (r < 0)
4745 return -ENOENT;
4746
4747 /* Get parent dev_t */
4748 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4749 return -ENOMEM;
4750
4751 r = read_one_line_file(p, &s);
4752 free(p);
4753
4754 if (r < 0)
4755 return r;
4756
4757 r = sscanf(s, "%u:%u", &m, &n);
4758 free(s);
4759
4760 if (r != 2)
4761 return -EINVAL;
4762
4763 /* Only return this if it is really good enough for us. */
4764 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4765 return -ENOMEM;
4766
4767 r = access(p, F_OK);
4768 free(p);
4769
4770 if (r >= 0) {
4771 *ret = makedev(m, n);
4772 return 0;
4773 }
4774
4775 return -ENOENT;
4776}
4777
8d53b453 4778int file_is_priv_sticky(const char *p) {
ad293f5a
LP
4779 struct stat st;
4780
4781 assert(p);
4782
4783 if (lstat(p, &st) < 0)
4784 return -errno;
4785
4786 return
8d53b453 4787 (st.st_uid == 0 || st.st_uid == getuid()) &&
ad293f5a
LP
4788 (st.st_mode & S_ISVTX);
4789}
94959f0f 4790
f41607a6
LP
4791static const char *const ioprio_class_table[] = {
4792 [IOPRIO_CLASS_NONE] = "none",
4793 [IOPRIO_CLASS_RT] = "realtime",
4794 [IOPRIO_CLASS_BE] = "best-effort",
4795 [IOPRIO_CLASS_IDLE] = "idle"
4796};
4797
f8b69d1d 4798DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
f41607a6
LP
4799
4800static const char *const sigchld_code_table[] = {
4801 [CLD_EXITED] = "exited",
4802 [CLD_KILLED] = "killed",
4803 [CLD_DUMPED] = "dumped",
4804 [CLD_TRAPPED] = "trapped",
4805 [CLD_STOPPED] = "stopped",
4806 [CLD_CONTINUED] = "continued",
4807};
4808
4809DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4810
4811static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4812 [LOG_FAC(LOG_KERN)] = "kern",
4813 [LOG_FAC(LOG_USER)] = "user",
4814 [LOG_FAC(LOG_MAIL)] = "mail",
4815 [LOG_FAC(LOG_DAEMON)] = "daemon",
4816 [LOG_FAC(LOG_AUTH)] = "auth",
4817 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4818 [LOG_FAC(LOG_LPR)] = "lpr",
4819 [LOG_FAC(LOG_NEWS)] = "news",
4820 [LOG_FAC(LOG_UUCP)] = "uucp",
4821 [LOG_FAC(LOG_CRON)] = "cron",
4822 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4823 [LOG_FAC(LOG_FTP)] = "ftp",
4824 [LOG_FAC(LOG_LOCAL0)] = "local0",
4825 [LOG_FAC(LOG_LOCAL1)] = "local1",
4826 [LOG_FAC(LOG_LOCAL2)] = "local2",
4827 [LOG_FAC(LOG_LOCAL3)] = "local3",
4828 [LOG_FAC(LOG_LOCAL4)] = "local4",
4829 [LOG_FAC(LOG_LOCAL5)] = "local5",
4830 [LOG_FAC(LOG_LOCAL6)] = "local6",
4831 [LOG_FAC(LOG_LOCAL7)] = "local7"
4832};
4833
f8b69d1d 4834DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
f41607a6
LP
4835
4836static const char *const log_level_table[] = {
4837 [LOG_EMERG] = "emerg",
4838 [LOG_ALERT] = "alert",
4839 [LOG_CRIT] = "crit",
4840 [LOG_ERR] = "err",
4841 [LOG_WARNING] = "warning",
4842 [LOG_NOTICE] = "notice",
4843 [LOG_INFO] = "info",
4844 [LOG_DEBUG] = "debug"
4845};
4846
f8b69d1d 4847DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
f41607a6
LP
4848
4849static const char* const sched_policy_table[] = {
4850 [SCHED_OTHER] = "other",
4851 [SCHED_BATCH] = "batch",
4852 [SCHED_IDLE] = "idle",
4853 [SCHED_FIFO] = "fifo",
4854 [SCHED_RR] = "rr"
4855};
4856
f8b69d1d 4857DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
f41607a6 4858
517d56b1 4859static const char* const rlimit_table[_RLIMIT_MAX] = {
f41607a6
LP
4860 [RLIMIT_CPU] = "LimitCPU",
4861 [RLIMIT_FSIZE] = "LimitFSIZE",
4862 [RLIMIT_DATA] = "LimitDATA",
4863 [RLIMIT_STACK] = "LimitSTACK",
4864 [RLIMIT_CORE] = "LimitCORE",
4865 [RLIMIT_RSS] = "LimitRSS",
4866 [RLIMIT_NOFILE] = "LimitNOFILE",
4867 [RLIMIT_AS] = "LimitAS",
4868 [RLIMIT_NPROC] = "LimitNPROC",
4869 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4870 [RLIMIT_LOCKS] = "LimitLOCKS",
4871 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4872 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4873 [RLIMIT_NICE] = "LimitNICE",
4874 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4875 [RLIMIT_RTTIME] = "LimitRTTIME"
4876};
4877
4878DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4879
4880static const char* const ip_tos_table[] = {
4881 [IPTOS_LOWDELAY] = "low-delay",
4882 [IPTOS_THROUGHPUT] = "throughput",
4883 [IPTOS_RELIABILITY] = "reliability",
4884 [IPTOS_LOWCOST] = "low-cost",
4885};
4886
f8b69d1d 4887DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
f41607a6 4888
4e240ab0 4889static const char *const __signal_table[] = {
f41607a6
LP
4890 [SIGHUP] = "HUP",
4891 [SIGINT] = "INT",
4892 [SIGQUIT] = "QUIT",
4893 [SIGILL] = "ILL",
4894 [SIGTRAP] = "TRAP",
4895 [SIGABRT] = "ABRT",
4896 [SIGBUS] = "BUS",
4897 [SIGFPE] = "FPE",
4898 [SIGKILL] = "KILL",
4899 [SIGUSR1] = "USR1",
4900 [SIGSEGV] = "SEGV",
4901 [SIGUSR2] = "USR2",
4902 [SIGPIPE] = "PIPE",
4903 [SIGALRM] = "ALRM",
4904 [SIGTERM] = "TERM",
4905#ifdef SIGSTKFLT
4906 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4907#endif
4908 [SIGCHLD] = "CHLD",
4909 [SIGCONT] = "CONT",
4910 [SIGSTOP] = "STOP",
4911 [SIGTSTP] = "TSTP",
4912 [SIGTTIN] = "TTIN",
4913 [SIGTTOU] = "TTOU",
4914 [SIGURG] = "URG",
4915 [SIGXCPU] = "XCPU",
4916 [SIGXFSZ] = "XFSZ",
4917 [SIGVTALRM] = "VTALRM",
4918 [SIGPROF] = "PROF",
4919 [SIGWINCH] = "WINCH",
4920 [SIGIO] = "IO",
4921 [SIGPWR] = "PWR",
4922 [SIGSYS] = "SYS"
4923};
4924
4e240ab0
MS
4925DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4926
4927const char *signal_to_string(int signo) {
ec202eae 4928 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4e240ab0
MS
4929 const char *name;
4930
4931 name = __signal_to_string(signo);
4932 if (name)
4933 return name;
4934
4935 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
fa70beaa 4936 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4e240ab0 4937 else
fa70beaa
LP
4938 snprintf(buf, sizeof(buf), "%d", signo);
4939
4e240ab0
MS
4940 return buf;
4941}
4942
4943int signal_from_string(const char *s) {
4944 int signo;
4945 int offset = 0;
4946 unsigned u;
4947
040f18ea 4948 signo = __signal_from_string(s);
4e240ab0
MS
4949 if (signo > 0)
4950 return signo;
4951
4952 if (startswith(s, "RTMIN+")) {
4953 s += 6;
4954 offset = SIGRTMIN;
4955 }
4956 if (safe_atou(s, &u) >= 0) {
4957 signo = (int) u + offset;
4958 if (signo > 0 && signo < _NSIG)
4959 return signo;
4960 }
7e8185ef 4961 return -EINVAL;
4e240ab0 4962}
65457142
FC
4963
4964bool kexec_loaded(void) {
4965 bool loaded = false;
4966 char *s;
4967
4968 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4969 if (s[0] == '1')
4970 loaded = true;
4971 free(s);
4972 }
4973 return loaded;
4974}
fb9de93d
LP
4975
4976int strdup_or_null(const char *a, char **b) {
4977 char *c;
4978
4979 assert(b);
4980
4981 if (!a) {
4982 *b = NULL;
4983 return 0;
4984 }
4985
4986 c = strdup(a);
4987 if (!c)
4988 return -ENOMEM;
4989
4990 *b = c;
4991 return 0;
4992}
64685e0c 4993
87d2c1ff
LP
4994int prot_from_flags(int flags) {
4995
4996 switch (flags & O_ACCMODE) {
4997
4998 case O_RDONLY:
4999 return PROT_READ;
5000
5001 case O_WRONLY:
5002 return PROT_WRITE;
5003
5004 case O_RDWR:
5005 return PROT_READ|PROT_WRITE;
5006
5007 default:
5008 return -EINVAL;
5009 }
7c99e0c1 5010}
689b9a22 5011
babfc091 5012char *format_bytes(char *buf, size_t l, off_t t) {
c0f99c21 5013 unsigned i;
babfc091
LP
5014
5015 static const struct {
5016 const char *suffix;
5017 off_t factor;
5018 } table[] = {
32895bb3
LP
5019 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5020 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
babfc091
LP
5021 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5022 { "G", 1024ULL*1024ULL*1024ULL },
5023 { "M", 1024ULL*1024ULL },
5024 { "K", 1024ULL },
5025 };
5026
5027 for (i = 0; i < ELEMENTSOF(table); i++) {
5028
5029 if (t >= table[i].factor) {
5030 snprintf(buf, l,
5031 "%llu.%llu%s",
5032 (unsigned long long) (t / table[i].factor),
5033 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5034 table[i].suffix);
5035
5036 goto finish;
5037 }
5038 }
5039
5040 snprintf(buf, l, "%lluB", (unsigned long long) t);
5041
5042finish:
5043 buf[l-1] = 0;
5044 return buf;
5045
5046}
55d7bfc1
LP
5047
5048void* memdup(const void *p, size_t l) {
5049 void *r;
5050
5051 assert(p);
5052
5053 r = malloc(l);
5054 if (!r)
5055 return NULL;
5056
5057 memcpy(r, p, l);
5058 return r;
5059}
bb99a35a
LP
5060
5061int fd_inc_sndbuf(int fd, size_t n) {
5062 int r, value;
5063 socklen_t l = sizeof(value);
5064
5065 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
92d75ca4 5066 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
bb99a35a
LP
5067 return 0;
5068
92d75ca4
LP
5069 /* If we have the privileges we will ignore the kernel limit. */
5070
bb99a35a 5071 value = (int) n;
92d75ca4
LP
5072 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
5073 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
5074 return -errno;
bb99a35a
LP
5075
5076 return 1;
5077}
5078
5079int fd_inc_rcvbuf(int fd, size_t n) {
5080 int r, value;
5081 socklen_t l = sizeof(value);
5082
5083 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
92d75ca4 5084 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
bb99a35a
LP
5085 return 0;
5086
92d75ca4 5087 /* If we have the privileges we will ignore the kernel limit. */
bb99a35a 5088
92d75ca4
LP
5089 value = (int) n;
5090 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
5091 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
5092 return -errno;
bb99a35a
LP
5093 return 1;
5094}
6bb92a16 5095
9bdc770c 5096int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
6bb92a16
LP
5097 pid_t parent_pid, agent_pid;
5098 int fd;
5099 bool stdout_is_tty, stderr_is_tty;
5100 unsigned n, i;
5101 va_list ap;
5102 char **l;
5103
5104 assert(pid);
5105 assert(path);
5106
5107 parent_pid = getpid();
5108
5109 /* Spawns a temporary TTY agent, making sure it goes away when
5110 * we go away */
5111
5112 agent_pid = fork();
5113 if (agent_pid < 0)
5114 return -errno;
5115
5116 if (agent_pid != 0) {
5117 *pid = agent_pid;
5118 return 0;
5119 }
5120
5121 /* In the child:
5122 *
5123 * Make sure the agent goes away when the parent dies */
5124 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5125 _exit(EXIT_FAILURE);
5126
5127 /* Check whether our parent died before we were able
5128 * to set the death signal */
5129 if (getppid() != parent_pid)
5130 _exit(EXIT_SUCCESS);
5131
5132 /* Don't leak fds to the agent */
9bdc770c 5133 close_all_fds(except, n_except);
6bb92a16
LP
5134
5135 stdout_is_tty = isatty(STDOUT_FILENO);
5136 stderr_is_tty = isatty(STDERR_FILENO);
5137
5138 if (!stdout_is_tty || !stderr_is_tty) {
5139 /* Detach from stdout/stderr. and reopen
5140 * /dev/tty for them. This is important to
5141 * ensure that when systemctl is started via
5142 * popen() or a similar call that expects to
5143 * read EOF we actually do generate EOF and
5144 * not delay this indefinitely by because we
5145 * keep an unused copy of stdin around. */
5146 fd = open("/dev/tty", O_WRONLY);
5147 if (fd < 0) {
5148 log_error("Failed to open /dev/tty: %m");
5149 _exit(EXIT_FAILURE);
5150 }
5151
5152 if (!stdout_is_tty)
5153 dup2(fd, STDOUT_FILENO);
5154
5155 if (!stderr_is_tty)
5156 dup2(fd, STDERR_FILENO);
5157
5158 if (fd > 2)
5159 close(fd);
5160 }
5161
5162 /* Count arguments */
5163 va_start(ap, path);
5164 for (n = 0; va_arg(ap, char*); n++)
5165 ;
5166 va_end(ap);
5167
5168 /* Allocate strv */
5169 l = alloca(sizeof(char *) * (n + 1));
5170
5171 /* Fill in arguments */
5172 va_start(ap, path);
5173 for (i = 0; i <= n; i++)
5174 l[i] = va_arg(ap, char*);
5175 va_end(ap);
5176
5177 execv(path, l);
5178 _exit(EXIT_FAILURE);
5179}
68faf98c
LP
5180
5181int setrlimit_closest(int resource, const struct rlimit *rlim) {
5182 struct rlimit highest, fixed;
5183
5184 assert(rlim);
5185
5186 if (setrlimit(resource, rlim) >= 0)
5187 return 0;
5188
5189 if (errno != EPERM)
5190 return -errno;
5191
5192 /* So we failed to set the desired setrlimit, then let's try
5193 * to get as close as we can */
5194 assert_se(getrlimit(resource, &highest) == 0);
5195
5196 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5197 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5198
5199 if (setrlimit(resource, &fixed) < 0)
5200 return -errno;
5201
5202 return 0;
5203}
3d9a4122 5204
ab94af92 5205int getenv_for_pid(pid_t pid, const char *field, char **_value) {
49aa47c7
LP
5206 _cleanup_fclose_ FILE *f = NULL;
5207 char *value = NULL;
ab94af92 5208 int r;
ab94af92
LP
5209 bool done = false;
5210 size_t l;
49aa47c7 5211 const char *path;
ab94af92 5212
49aa47c7 5213 assert(pid >= 0);
ab94af92
LP
5214 assert(field);
5215 assert(_value);
5216
b68fa010 5217 path = procfs_file_alloca(pid, "environ");
ab94af92
LP
5218
5219 f = fopen(path, "re");
5220 if (!f)
5221 return -errno;
5222
5223 l = strlen(field);
5224 r = 0;
5225
5226 do {
5227 char line[LINE_MAX];
5228 unsigned i;
5229
5230 for (i = 0; i < sizeof(line)-1; i++) {
5231 int c;
5232
5233 c = getc(f);
5234 if (_unlikely_(c == EOF)) {
5235 done = true;
5236 break;
5237 } else if (c == 0)
5238 break;
5239
5240 line[i] = c;
5241 }
5242 line[i] = 0;
5243
5244 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5245 value = strdup(line + l + 1);
49aa47c7
LP
5246 if (!value)
5247 return -ENOMEM;
ab94af92
LP
5248
5249 r = 1;
5250 break;
5251 }
5252
5253 } while (!done);
5254
49aa47c7 5255 *_value = value;
ab94af92
LP
5256 return r;
5257}
d889a206 5258
49dbfa7b
LP
5259bool is_valid_documentation_url(const char *url) {
5260 assert(url);
5261
5262 if (startswith(url, "http://") && url[7])
5263 return true;
5264
5265 if (startswith(url, "https://") && url[8])
5266 return true;
5267
5268 if (startswith(url, "file:") && url[5])
5269 return true;
5270
5271 if (startswith(url, "info:") && url[5])
5272 return true;
5273
5274 if (startswith(url, "man:") && url[4])
5275 return true;
5276
5277 return false;
5278}
9be346c9
HH
5279
5280bool in_initrd(void) {
73020ab2 5281 static int saved = -1;
825c6fe5 5282 struct statfs s;
8f33b5b8 5283
825c6fe5
LP
5284 if (saved >= 0)
5285 return saved;
5286
5287 /* We make two checks here:
5288 *
5289 * 1. the flag file /etc/initrd-release must exist
5290 * 2. the root file system must be a memory file system
5291 *
5292 * The second check is extra paranoia, since misdetecting an
5293 * initrd can have bad bad consequences due the initrd
5294 * emptying when transititioning to the main systemd.
5295 */
5296
5297 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5298 statfs("/", &s) >= 0 &&
943aad8c 5299 is_temporary_fs(&s);
9be346c9 5300
8f33b5b8 5301 return saved;
9be346c9 5302}
069cfc85
LP
5303
5304void warn_melody(void) {
e67f47e5 5305 _cleanup_close_ int fd = -1;
069cfc85
LP
5306
5307 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5308 if (fd < 0)
5309 return;
5310
040f18ea 5311 /* Yeah, this is synchronous. Kinda sucks. But well... */
069cfc85
LP
5312
5313 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5314 usleep(125*USEC_PER_MSEC);
5315
5316 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5317 usleep(125*USEC_PER_MSEC);
5318
5319 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5320 usleep(125*USEC_PER_MSEC);
5321
5322 ioctl(fd, KIOCSOUND, 0);
069cfc85 5323}
cd3bd60a
LP
5324
5325int make_console_stdio(void) {
5326 int fd, r;
5327
5328 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5329
3a43da28 5330 fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
cd3bd60a
LP
5331 if (fd < 0) {
5332 log_error("Failed to acquire terminal: %s", strerror(-fd));
5333 return fd;
5334 }
5335
5336 r = make_stdio(fd);
5337 if (r < 0) {
5338 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5339 return r;
5340 }
5341
5342 return 0;
5343}
7c5f152a
LP
5344
5345int get_home_dir(char **_h) {
2cfbd749 5346 struct passwd *p;
7c5f152a 5347 const char *e;
2cfbd749 5348 char *h;
7c5f152a 5349 uid_t u;
7c5f152a
LP
5350
5351 assert(_h);
5352
5353 /* Take the user specified one */
9a00f57a
LP
5354 e = secure_getenv("HOME");
5355 if (e && path_is_absolute(e)) {
7c5f152a
LP
5356 h = strdup(e);
5357 if (!h)
5358 return -ENOMEM;
5359
5360 *_h = h;
5361 return 0;
5362 }
5363
5364 /* Hardcode home directory for root to avoid NSS */
5365 u = getuid();
5366 if (u == 0) {
5367 h = strdup("/root");
5368 if (!h)
5369 return -ENOMEM;
5370
5371 *_h = h;
5372 return 0;
5373 }
5374
5375 /* Check the database... */
5376 errno = 0;
5377 p = getpwuid(u);
5378 if (!p)
bcb161b0 5379 return errno > 0 ? -errno : -ESRCH;
7c5f152a
LP
5380
5381 if (!path_is_absolute(p->pw_dir))
5382 return -EINVAL;
5383
5384 h = strdup(p->pw_dir);
5385 if (!h)
5386 return -ENOMEM;
5387
5388 *_h = h;
5389 return 0;
5390}
5391
2cfbd749
LP
5392int get_shell(char **_s) {
5393 struct passwd *p;
5394 const char *e;
5395 char *s;
5396 uid_t u;
5397
5398 assert(_s);
5399
5400 /* Take the user specified one */
5401 e = getenv("SHELL");
5402 if (e) {
5403 s = strdup(e);
5404 if (!s)
5405 return -ENOMEM;
5406
5407 *_s = s;
5408 return 0;
5409 }
5410
5411 /* Hardcode home directory for root to avoid NSS */
5412 u = getuid();
5413 if (u == 0) {
5414 s = strdup("/bin/sh");
5415 if (!s)
5416 return -ENOMEM;
5417
5418 *_s = s;
5419 return 0;
5420 }
5421
5422 /* Check the database... */
5423 errno = 0;
5424 p = getpwuid(u);
5425 if (!p)
5426 return errno > 0 ? -errno : -ESRCH;
5427
5428 if (!path_is_absolute(p->pw_shell))
5429 return -EINVAL;
5430
5431 s = strdup(p->pw_shell);
5432 if (!s)
5433 return -ENOMEM;
5434
5435 *_s = s;
5436 return 0;
5437}
5438
0b507b17
LP
5439bool filename_is_safe(const char *p) {
5440
5441 if (isempty(p))
5442 return false;
5443
5444 if (strchr(p, '/'))
5445 return false;
5446
5447 if (streq(p, "."))
5448 return false;
5449
5450 if (streq(p, ".."))
5451 return false;
5452
5453 if (strlen(p) > FILENAME_MAX)
5454 return false;
5455
5456 return true;
5457}
5458
5459bool string_is_safe(const char *p) {
5460 const char *t;
5461
6294aa76
LP
5462 if (!p)
5463 return false;
0b507b17
LP
5464
5465 for (t = p; *t; t++) {
01539d6e 5466 if (*t > 0 && *t < ' ')
0b507b17
LP
5467 return false;
5468
6294aa76 5469 if (strchr("\\\"\'\0x7f", *t))
0b507b17
LP
5470 return false;
5471 }
5472
5473 return true;
5474}
cfbc22ab 5475
ac4c8d6d 5476/**
6294aa76
LP
5477 * Check if a string contains control characters. If 'ok' is non-NULL
5478 * it may be a string containing additional CCs to be considered OK.
ac4c8d6d 5479 */
6294aa76 5480bool string_has_cc(const char *p, const char *ok) {
4d1a6904
LP
5481 const char *t;
5482
5483 assert(p);
5484
3a8a9163 5485 for (t = p; *t; t++) {
6294aa76 5486 if (ok && strchr(ok, *t))
1cb1767a 5487 continue;
6294aa76
LP
5488
5489 if (*t > 0 && *t < ' ')
4d1a6904
LP
5490 return true;
5491
3a8a9163
LP
5492 if (*t == 127)
5493 return true;
5494 }
5495
4d1a6904
LP
5496 return false;
5497}
5498
e884315e
LP
5499bool path_is_safe(const char *p) {
5500
5501 if (isempty(p))
5502 return false;
5503
5504 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5505 return false;
5506
5507 if (strlen(p) > PATH_MAX)
5508 return false;
5509
5510 /* The following two checks are not really dangerous, but hey, they still are confusing */
5511 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5512 return false;
5513
5514 if (strstr(p, "//"))
5515 return false;
5516
5517 return true;
5518}
5519
a9e12476
KS
5520/* hey glibc, APIs with callbacks without a user pointer are so useless */
5521void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
1c574591 5522 int (*compar) (const void *, const void *, void *), void *arg) {
a9e12476
KS
5523 size_t l, u, idx;
5524 const void *p;
5525 int comparison;
5526
5527 l = 0;
5528 u = nmemb;
5529 while (l < u) {
5530 idx = (l + u) / 2;
5531 p = (void *)(((const char *) base) + (idx * size));
5532 comparison = compar(key, p, arg);
5533 if (comparison < 0)
5534 u = idx;
5535 else if (comparison > 0)
5536 l = idx + 1;
5537 else
5538 return (void *)p;
5539 }
5540 return NULL;
5541}
09017585
MS
5542
5543bool is_locale_utf8(void) {
5544 const char *set;
5545 static int cached_answer = -1;
5546
5547 if (cached_answer >= 0)
5548 goto out;
5549
5550 if (!setlocale(LC_ALL, "")) {
5551 cached_answer = true;
5552 goto out;
5553 }
5554
5555 set = nl_langinfo(CODESET);
5556 if (!set) {
5557 cached_answer = true;
5558 goto out;
5559 }
5560
f168c273 5561 if (streq(set, "UTF-8")) {
fee79e01
HH
5562 cached_answer = true;
5563 goto out;
5564 }
5565
6cf2f1d9
HH
5566 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5567 * unset and everything can do to UTF-8 nowadays. */
fee79e01
HH
5568 set = setlocale(LC_CTYPE, NULL);
5569 if (!set) {
5570 cached_answer = true;
5571 goto out;
5572 }
5573
6cf2f1d9
HH
5574 /* Check result, but ignore the result if C was set
5575 * explicitly. */
5576 cached_answer =
5577 streq(set, "C") &&
5578 !getenv("LC_ALL") &&
5579 !getenv("LC_CTYPE") &&
5580 !getenv("LANG");
fee79e01 5581
09017585 5582out:
6cf2f1d9 5583 return (bool) cached_answer;
09017585 5584}
c339d977
MS
5585
5586const char *draw_special_char(DrawSpecialChar ch) {
5587 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
6b01f1d3 5588
c339d977 5589 /* UTF-8 */ {
6b01f1d3 5590 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
45a5ff0d
MS
5591 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5592 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
55c0b89c 5593 [DRAW_TREE_SPACE] = " ", /* */
6b01f1d3
LP
5594 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
5595 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
5596 [DRAW_ARROW] = "\342\206\222", /* → */
13f8b8cb 5597 [DRAW_DASH] = "\342\200\223", /* – */
c339d977 5598 },
6b01f1d3 5599
c339d977 5600 /* ASCII fallback */ {
6b01f1d3 5601 [DRAW_TREE_VERTICAL] = "| ",
45a5ff0d
MS
5602 [DRAW_TREE_BRANCH] = "|-",
5603 [DRAW_TREE_RIGHT] = "`-",
55c0b89c 5604 [DRAW_TREE_SPACE] = " ",
6b01f1d3
LP
5605 [DRAW_TRIANGULAR_BULLET] = ">",
5606 [DRAW_BLACK_CIRCLE] = "*",
5607 [DRAW_ARROW] = "->",
13f8b8cb 5608 [DRAW_DASH] = "-",
c339d977
MS
5609 }
5610 };
5611
5612 return draw_table[!is_locale_utf8()][ch];
5613}
409bc9c3
LP
5614
5615char *strreplace(const char *text, const char *old_string, const char *new_string) {
5616 const char *f;
5617 char *t, *r;
5618 size_t l, old_len, new_len;
5619
5620 assert(text);
5621 assert(old_string);
5622 assert(new_string);
5623
5624 old_len = strlen(old_string);
5625 new_len = strlen(new_string);
5626
5627 l = strlen(text);
5628 r = new(char, l+1);
5629 if (!r)
5630 return NULL;
5631
5632 f = text;
5633 t = r;
5634 while (*f) {
5635 char *a;
5636 size_t d, nl;
5637
5638 if (!startswith(f, old_string)) {
5639 *(t++) = *(f++);
5640 continue;
5641 }
5642
5643 d = t - r;
5644 nl = l - old_len + new_len;
5645 a = realloc(r, nl + 1);
5646 if (!a)
5647 goto oom;
5648
5649 l = nl;
5650 r = a;
5651 t = r + d;
5652
5653 t = stpcpy(t, new_string);
5654 f += old_len;
5655 }
5656
5657 *t = 0;
5658 return r;
5659
5660oom:
5661 free(r);
5662 return NULL;
5663}
e8bc0ea2
LP
5664
5665char *strip_tab_ansi(char **ibuf, size_t *_isz) {
660ddc72 5666 const char *i, *begin = NULL;
e8bc0ea2
LP
5667 enum {
5668 STATE_OTHER,
5669 STATE_ESCAPE,
5670 STATE_BRACKET
5671 } state = STATE_OTHER;
5672 char *obuf = NULL;
5673 size_t osz = 0, isz;
5674 FILE *f;
5675
5676 assert(ibuf);
5677 assert(*ibuf);
5678
5679 /* Strips ANSI color and replaces TABs by 8 spaces */
5680
5681 isz = _isz ? *_isz : strlen(*ibuf);
5682
5683 f = open_memstream(&obuf, &osz);
5684 if (!f)
5685 return NULL;
5686
5687 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5688
5689 switch (state) {
5690
5691 case STATE_OTHER:
5692 if (i >= *ibuf + isz) /* EOT */
5693 break;
5694 else if (*i == '\x1B')
5695 state = STATE_ESCAPE;
5696 else if (*i == '\t')
5697 fputs(" ", f);
5698 else
5699 fputc(*i, f);
5700 break;
5701
5702 case STATE_ESCAPE:
5703 if (i >= *ibuf + isz) { /* EOT */
5704 fputc('\x1B', f);
5705 break;
5706 } else if (*i == '[') {
5707 state = STATE_BRACKET;
5708 begin = i + 1;
5709 } else {
5710 fputc('\x1B', f);
5711 fputc(*i, f);
5712 state = STATE_OTHER;
5713 }
5714
5715 break;
5716
5717 case STATE_BRACKET:
5718
5719 if (i >= *ibuf + isz || /* EOT */
5720 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5721 fputc('\x1B', f);
5722 fputc('[', f);
5723 state = STATE_OTHER;
5724 i = begin-1;
5725 } else if (*i == 'm')
5726 state = STATE_OTHER;
5727 break;
5728 }
5729 }
5730
5731 if (ferror(f)) {
5732 fclose(f);
5733 free(obuf);
5734 return NULL;
5735 }
5736
5737 fclose(f);
5738
5739 free(*ibuf);
5740 *ibuf = obuf;
5741
5742 if (_isz)
5743 *_isz = osz;
5744
5745 return obuf;
5746}
240dbaa4
LP
5747
5748int on_ac_power(void) {
5749 bool found_offline = false, found_online = false;
5750 _cleanup_closedir_ DIR *d = NULL;
5751
5752 d = opendir("/sys/class/power_supply");
5753 if (!d)
5754 return -errno;
5755
5756 for (;;) {
5757 struct dirent *de;
240dbaa4
LP
5758 _cleanup_close_ int fd = -1, device = -1;
5759 char contents[6];
5760 ssize_t n;
240dbaa4 5761
3fd11280
FW
5762 errno = 0;
5763 de = readdir(d);
5764 if (!de && errno != 0)
5765 return -errno;
240dbaa4
LP
5766
5767 if (!de)
5768 break;
5769
5770 if (ignore_file(de->d_name))
5771 continue;
5772
5773 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5774 if (device < 0) {
5775 if (errno == ENOENT || errno == ENOTDIR)
5776 continue;
5777
5778 return -errno;
5779 }
5780
5781 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5782 if (fd < 0) {
5783 if (errno == ENOENT)
5784 continue;
5785
5786 return -errno;
5787 }
5788
5789 n = read(fd, contents, sizeof(contents));
5790 if (n < 0)
5791 return -errno;
5792
5793 if (n != 6 || memcmp(contents, "Mains\n", 6))
5794 continue;
5795
03e334a1 5796 safe_close(fd);
240dbaa4
LP
5797 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5798 if (fd < 0) {
5799 if (errno == ENOENT)
5800 continue;
5801
5802 return -errno;
5803 }
5804
5805 n = read(fd, contents, sizeof(contents));
5806 if (n < 0)
5807 return -errno;
5808
5809 if (n != 2 || contents[1] != '\n')
5810 return -EIO;
5811
5812 if (contents[0] == '1') {
5813 found_online = true;
5814 break;
5815 } else if (contents[0] == '0')
5816 found_offline = true;
5817 else
5818 return -EIO;
5819 }
5820
5821 return found_online || !found_offline;
5822}
fabe5c0e 5823
4cf7ea55 5824static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
fabe5c0e
LP
5825 char **i;
5826
5827 assert(path);
5828 assert(mode);
5829 assert(_f);
5830
7d8da2c9 5831 if (!path_strv_resolve_uniq(search, root))
fabe5c0e
LP
5832 return -ENOMEM;
5833
5834 STRV_FOREACH(i, search) {
5835 _cleanup_free_ char *p = NULL;
5836 FILE *f;
5837
375eadd9
MM
5838 if (root)
5839 p = strjoin(root, *i, "/", path, NULL);
5840 else
5841 p = strjoin(*i, "/", path, NULL);
fabe5c0e
LP
5842 if (!p)
5843 return -ENOMEM;
5844
5845 f = fopen(p, mode);
5846 if (f) {
5847 *_f = f;
5848 return 0;
5849 }
5850
5851 if (errno != ENOENT)
5852 return -errno;
5853 }
5854
5855 return -ENOENT;
5856}
5857
4cf7ea55 5858int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
fabe5c0e
LP
5859 _cleanup_strv_free_ char **copy = NULL;
5860
5861 assert(path);
5862 assert(mode);
5863 assert(_f);
5864
5865 if (path_is_absolute(path)) {
5866 FILE *f;
5867
5868 f = fopen(path, mode);
5869 if (f) {
5870 *_f = f;
5871 return 0;
5872 }
5873
5874 return -errno;
5875 }
5876
5877 copy = strv_copy((char**) search);
5878 if (!copy)
5879 return -ENOMEM;
5880
4cf7ea55 5881 return search_and_fopen_internal(path, mode, root, copy, _f);
fabe5c0e
LP
5882}
5883
4cf7ea55 5884int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
fabe5c0e
LP
5885 _cleanup_strv_free_ char **s = NULL;
5886
5887 if (path_is_absolute(path)) {
5888 FILE *f;
5889
5890 f = fopen(path, mode);
5891 if (f) {
5892 *_f = f;
5893 return 0;
5894 }
5895
5896 return -errno;
5897 }
5898
5899 s = strv_split_nulstr(search);
5900 if (!s)
5901 return -ENOMEM;
5902
4cf7ea55 5903 return search_and_fopen_internal(path, mode, root, s, _f);
fabe5c0e 5904}
c17ec25e 5905
66e35261
LP
5906char *strextend(char **x, ...) {
5907 va_list ap;
5908 size_t f, l;
5909 char *r, *p;
5910
5911 assert(x);
5912
5913 l = f = *x ? strlen(*x) : 0;
5914
5915 va_start(ap, x);
5916 for (;;) {
5917 const char *t;
5918 size_t n;
5919
5920 t = va_arg(ap, const char *);
5921 if (!t)
5922 break;
5923
5924 n = strlen(t);
5925 if (n > ((size_t) -1) - l) {
5926 va_end(ap);
5927 return NULL;
5928 }
5929
5930 l += n;
5931 }
5932 va_end(ap);
5933
5934 r = realloc(*x, l+1);
5935 if (!r)
5936 return NULL;
5937
5938 p = r + f;
5939
5940 va_start(ap, x);
5941 for (;;) {
5942 const char *t;
5943
5944 t = va_arg(ap, const char *);
5945 if (!t)
5946 break;
5947
5948 p = stpcpy(p, t);
5949 }
5950 va_end(ap);
5951
5952 *p = 0;
5953 *x = r;
5954
5955 return r + l;
5956}
9a17484d
LP
5957
5958char *strrep(const char *s, unsigned n) {
5959 size_t l;
5960 char *r, *p;
5961 unsigned i;
5962
5963 assert(s);
5964
5965 l = strlen(s);
5966 p = r = malloc(l * n + 1);
5967 if (!r)
5968 return NULL;
5969
5970 for (i = 0; i < n; i++)
5971 p = stpcpy(p, s);
5972
5973 *p = 0;
5974 return r;
5975}
392d5b37 5976
ca2d3784
ZJS
5977void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
5978 size_t a, newalloc;
392d5b37
LP
5979 void *q;
5980
98088803 5981 assert(p);
e93c33d4
SL
5982 assert(allocated);
5983
392d5b37
LP
5984 if (*allocated >= need)
5985 return *p;
5986
ca2d3784
ZJS
5987 newalloc = MAX(need * 2, 64u / size);
5988 a = newalloc * size;
98088803
LP
5989
5990 /* check for overflows */
ca2d3784 5991 if (a < size * need)
98088803
LP
5992 return NULL;
5993
392d5b37
LP
5994 q = realloc(*p, a);
5995 if (!q)
5996 return NULL;
5997
5998 *p = q;
ca2d3784 5999 *allocated = newalloc;
392d5b37
LP
6000 return q;
6001}
aa96c6cb 6002
ca2d3784 6003void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
98088803 6004 size_t prev;
4545a231
DH
6005 uint8_t *q;
6006
98088803
LP
6007 assert(p);
6008 assert(allocated);
6009
6010 prev = *allocated;
6011
ca2d3784 6012 q = greedy_realloc(p, allocated, need, size);
4545a231
DH
6013 if (!q)
6014 return NULL;
6015
6016 if (*allocated > prev)
ca2d3784 6017 memzero(q + prev * size, (*allocated - prev) * size);
4545a231
DH
6018
6019 return q;
6020}
6021
aa96c6cb
LP
6022bool id128_is_valid(const char *s) {
6023 size_t i, l;
6024
6025 l = strlen(s);
6026 if (l == 32) {
6027
6028 /* Simple formatted 128bit hex string */
6029
6030 for (i = 0; i < l; i++) {
6031 char c = s[i];
6032
6033 if (!(c >= '0' && c <= '9') &&
6034 !(c >= 'a' && c <= 'z') &&
6035 !(c >= 'A' && c <= 'Z'))
6036 return false;
6037 }
6038
6039 } else if (l == 36) {
6040
6041 /* Formatted UUID */
6042
6043 for (i = 0; i < l; i++) {
6044 char c = s[i];
6045
6046 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
6047 if (c != '-')
6048 return false;
6049 } else {
6050 if (!(c >= '0' && c <= '9') &&
6051 !(c >= 'a' && c <= 'z') &&
6052 !(c >= 'A' && c <= 'Z'))
6053 return false;
6054 }
6055 }
6056
6057 } else
6058 return false;
6059
6060 return true;
6061}
7085053a 6062
d4ac85c6
LP
6063int split_pair(const char *s, const char *sep, char **l, char **r) {
6064 char *x, *a, *b;
6065
6066 assert(s);
6067 assert(sep);
6068 assert(l);
6069 assert(r);
6070
6071 if (isempty(sep))
6072 return -EINVAL;
6073
6074 x = strstr(s, sep);
6075 if (!x)
6076 return -EINVAL;
6077
6078 a = strndup(s, x - s);
6079 if (!a)
6080 return -ENOMEM;
6081
6082 b = strdup(x + strlen(sep));
6083 if (!b) {
6084 free(a);
6085 return -ENOMEM;
6086 }
6087
6088 *l = a;
6089 *r = b;
6090
6091 return 0;
6092}
295edddf 6093
74df0fca 6094int shall_restore_state(void) {
059cb385 6095 _cleanup_free_ char *line = NULL;
a2a5291b 6096 const char *word, *state;
295edddf 6097 size_t l;
74df0fca 6098 int r;
295edddf 6099
74df0fca
LP
6100 r = proc_cmdline(&line);
6101 if (r < 0)
6102 return r;
6103 if (r == 0) /* Container ... */
6104 return 1;
295edddf 6105
059cb385 6106 r = 1;
74df0fca 6107
a2a5291b 6108 FOREACH_WORD_QUOTED(word, l, line, state) {
059cb385
LP
6109 const char *e;
6110 char n[l+1];
6111 int k;
6112
a2a5291b 6113 memcpy(n, word, l);
059cb385
LP
6114 n[l] = 0;
6115
6116 e = startswith(n, "systemd.restore_state=");
6117 if (!e)
6118 continue;
6119
6120 k = parse_boolean(e);
6121 if (k >= 0)
6122 r = k;
6123 }
6124
6125 return r;
74df0fca
LP
6126}
6127
6128int proc_cmdline(char **ret) {
6129 int r;
6130
6131 if (detect_container(NULL) > 0) {
39883f62 6132 char *buf = NULL, *p;
02bb6cda
LP
6133 size_t sz = 0;
6134
6135 r = read_full_file("/proc/1/cmdline", &buf, &sz);
6136 if (r < 0)
6137 return r;
6138
6139 for (p = buf; p + 1 < buf + sz; p++)
6140 if (*p == 0)
6141 *p = ' ';
6142
059cb385 6143 *p = 0;
02bb6cda
LP
6144 *ret = buf;
6145 return 1;
295edddf
TG
6146 }
6147
74df0fca
LP
6148 r = read_one_line_file("/proc/cmdline", ret);
6149 if (r < 0)
6150 return r;
295edddf 6151
74df0fca 6152 return 1;
295edddf 6153}
bc9fd78c 6154
059cb385 6155int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
141a79f4 6156 _cleanup_free_ char *line = NULL;
a2a5291b 6157 const char *w, *state;
141a79f4
ZJS
6158 size_t l;
6159 int r;
6160
059cb385
LP
6161 assert(parse_item);
6162
141a79f4
ZJS
6163 r = proc_cmdline(&line);
6164 if (r < 0)
6165 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
6166 if (r <= 0)
6167 return 0;
6168
6169 FOREACH_WORD_QUOTED(w, l, line, state) {
059cb385 6170 char word[l+1], *value;
141a79f4 6171
059cb385
LP
6172 memcpy(word, w, l);
6173 word[l] = 0;
141a79f4 6174
059cb385
LP
6175 /* Filter out arguments that are intended only for the
6176 * initrd */
6177 if (!in_initrd() && startswith(word, "rd."))
6178 continue;
6179
6180 value = strchr(word, '=');
6181 if (value)
6182 *(value++) = 0;
6183
6184 r = parse_item(word, value);
6185 if (r < 0)
141a79f4 6186 return r;
141a79f4
ZJS
6187 }
6188
6189 return 0;
6190}
6191
bc9fd78c
LP
6192int container_get_leader(const char *machine, pid_t *pid) {
6193 _cleanup_free_ char *s = NULL, *class = NULL;
6194 const char *p;
6195 pid_t leader;
6196 int r;
6197
6198 assert(machine);
6199 assert(pid);
6200
6201 p = strappenda("/run/systemd/machines/", machine);
6202 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
6203 if (r == -ENOENT)
6204 return -EHOSTDOWN;
6205 if (r < 0)
6206 return r;
6207 if (!s)
6208 return -EIO;
6209
6210 if (!streq_ptr(class, "container"))
6211 return -EIO;
6212
6213 r = parse_pid(s, &leader);
6214 if (r < 0)
6215 return r;
6216 if (leader <= 1)
6217 return -EIO;
6218
6219 *pid = leader;
6220 return 0;
6221}
6222
878cd7e9
LP
6223int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
6224 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
359a06aa 6225 int rfd = -1;
bc9fd78c
LP
6226
6227 assert(pid >= 0);
bc9fd78c 6228
878cd7e9
LP
6229 if (mntns_fd) {
6230 const char *mntns;
a4475f57 6231
878cd7e9
LP
6232 mntns = procfs_file_alloca(pid, "ns/mnt");
6233 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6234 if (mntnsfd < 0)
6235 return -errno;
6236 }
bc9fd78c 6237
878cd7e9
LP
6238 if (pidns_fd) {
6239 const char *pidns;
6240
6241 pidns = procfs_file_alloca(pid, "ns/pid");
6242 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6243 if (pidnsfd < 0)
6244 return -errno;
6245 }
6246
6247 if (netns_fd) {
6248 const char *netns;
6249
6250 netns = procfs_file_alloca(pid, "ns/net");
6251 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6252 if (netnsfd < 0)
6253 return -errno;
6254 }
6255
6256 if (root_fd) {
6257 const char *root;
6258
6259 root = procfs_file_alloca(pid, "root");
6260 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
6261 if (rfd < 0)
6262 return -errno;
6263 }
6264
6265 if (pidns_fd)
6266 *pidns_fd = pidnsfd;
bc9fd78c 6267
878cd7e9
LP
6268 if (mntns_fd)
6269 *mntns_fd = mntnsfd;
6270
6271 if (netns_fd)
6272 *netns_fd = netnsfd;
6273
6274 if (root_fd)
6275 *root_fd = rfd;
6276
6277 pidnsfd = mntnsfd = netnsfd = -1;
bc9fd78c
LP
6278
6279 return 0;
6280}
6281
878cd7e9 6282int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
bc9fd78c 6283
878cd7e9
LP
6284 if (pidns_fd >= 0)
6285 if (setns(pidns_fd, CLONE_NEWPID) < 0)
6286 return -errno;
a4475f57 6287
878cd7e9
LP
6288 if (mntns_fd >= 0)
6289 if (setns(mntns_fd, CLONE_NEWNS) < 0)
6290 return -errno;
bc9fd78c 6291
878cd7e9
LP
6292 if (netns_fd >= 0)
6293 if (setns(netns_fd, CLONE_NEWNET) < 0)
6294 return -errno;
bc9fd78c 6295
878cd7e9
LP
6296 if (root_fd >= 0) {
6297 if (fchdir(root_fd) < 0)
6298 return -errno;
6299
6300 if (chroot(".") < 0)
6301 return -errno;
6302 }
bc9fd78c 6303
5e2b3214
LP
6304 if (setresgid(0, 0, 0) < 0)
6305 return -errno;
6306
878cd7e9
LP
6307 if (setgroups(0, NULL) < 0)
6308 return -errno;
6309
5e2b3214
LP
6310 if (setresuid(0, 0, 0) < 0)
6311 return -errno;
6312
bc9fd78c
LP
6313 return 0;
6314}
bf108e55 6315
9f5650ae
LP
6316bool pid_is_unwaited(pid_t pid) {
6317 /* Checks whether a PID is still valid at all, including a zombie */
6318
bf108e55
LP
6319 if (pid <= 0)
6320 return false;
6321
6322 if (kill(pid, 0) >= 0)
6323 return true;
6324
6325 return errno != ESRCH;
6326}
eff05270 6327
9f5650ae
LP
6328bool pid_is_alive(pid_t pid) {
6329 int r;
6330
6331 /* Checks whether a PID is still valid and not a zombie */
6332
6333 if (pid <= 0)
6334 return false;
6335
6336 r = get_process_state(pid);
6337 if (r == -ENOENT || r == 'Z')
6338 return false;
6339
6340 return true;
6341}
6342
eff05270
LP
6343int getpeercred(int fd, struct ucred *ucred) {
6344 socklen_t n = sizeof(struct ucred);
6345 struct ucred u;
6346 int r;
6347
6348 assert(fd >= 0);
6349 assert(ucred);
6350
6351 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6352 if (r < 0)
6353 return -errno;
6354
6355 if (n != sizeof(struct ucred))
6356 return -EIO;
6357
6358 /* Check if the data is actually useful and not suppressed due
6359 * to namespacing issues */
6360 if (u.pid <= 0)
6361 return -ENODATA;
6362
6363 *ucred = u;
6364 return 0;
6365}
6366
6367int getpeersec(int fd, char **ret) {
6368 socklen_t n = 64;
6369 char *s;
6370 int r;
6371
6372 assert(fd >= 0);
6373 assert(ret);
6374
6375 s = new0(char, n);
6376 if (!s)
6377 return -ENOMEM;
6378
6379 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6380 if (r < 0) {
6381 free(s);
6382
6383 if (errno != ERANGE)
6384 return -errno;
6385
6386 s = new0(char, n);
6387 if (!s)
6388 return -ENOMEM;
6389
6390 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6391 if (r < 0) {
6392 free(s);
6393 return -errno;
6394 }
6395 }
6396
ae98841e
LP
6397 if (isempty(s)) {
6398 free(s);
6399 return -ENOTSUP;
6400 }
6401
eff05270
LP
6402 *ret = s;
6403 return 0;
6404}
8e33886e 6405
0f010ef2 6406/* This is much like like mkostemp() but is subject to umask(). */
65b3903f 6407int mkostemp_safe(char *pattern, int flags) {
2d5bdf5b 6408 _cleanup_umask_ mode_t u;
0f010ef2 6409 int fd;
65b3903f 6410
d37a91e8 6411 assert(pattern);
65b3903f 6412
2d5bdf5b
LP
6413 u = umask(077);
6414
0f010ef2
ZJS
6415 fd = mkostemp(pattern, flags);
6416 if (fd < 0)
6417 return -errno;
65b3903f 6418
0f010ef2 6419 return fd;
65b3903f
ZJS
6420}
6421
8e33886e 6422int open_tmpfile(const char *path, int flags) {
8e33886e 6423 char *p;
a6afc4ae
LP
6424 int fd;
6425
6426 assert(path);
8e33886e
ZJS
6427
6428#ifdef O_TMPFILE
7736202c
LP
6429 /* Try O_TMPFILE first, if it is supported */
6430 fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
8e33886e
ZJS
6431 if (fd >= 0)
6432 return fd;
6433#endif
7736202c
LP
6434
6435 /* Fall back to unguessable name + unlinking */
8e33886e
ZJS
6436 p = strappenda(path, "/systemd-tmp-XXXXXX");
6437
a6afc4ae 6438 fd = mkostemp_safe(p, flags);
8e33886e 6439 if (fd < 0)
65b3903f 6440 return fd;
8e33886e
ZJS
6441
6442 unlink(p);
6443 return fd;
6444}
fdb9161c
LP
6445
6446int fd_warn_permissions(const char *path, int fd) {
6447 struct stat st;
6448
6449 if (fstat(fd, &st) < 0)
6450 return -errno;
6451
6452 if (st.st_mode & 0111)
6453 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6454
6455 if (st.st_mode & 0002)
6456 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6457
6458 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6459 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);
6460
6461 return 0;
6462}
6afc95b7 6463
ac45f971 6464unsigned long personality_from_string(const char *p) {
6afc95b7
LP
6465
6466 /* Parse a personality specifier. We introduce our own
6467 * identifiers that indicate specific ABIs, rather than just
6468 * hints regarding the register size, since we want to keep
6469 * things open for multiple locally supported ABIs for the
6470 * same register size. We try to reuse the ABI identifiers
6471 * used by libseccomp. */
6472
6473#if defined(__x86_64__)
6474
6475 if (streq(p, "x86"))
6476 return PER_LINUX32;
6477
6478 if (streq(p, "x86-64"))
6479 return PER_LINUX;
6480
6481#elif defined(__i386__)
6482
6483 if (streq(p, "x86"))
6484 return PER_LINUX;
6485#endif
6486
6487 /* personality(7) documents that 0xffffffffUL is used for
6488 * querying the current personality, hence let's use that here
6489 * as error indicator. */
6490 return 0xffffffffUL;
6491}
ac45f971
LP
6492
6493const char* personality_to_string(unsigned long p) {
6494
6495#if defined(__x86_64__)
6496
6497 if (p == PER_LINUX32)
6498 return "x86";
6499
6500 if (p == PER_LINUX)
6501 return "x86-64";
6502
6503#elif defined(__i386__)
6504
6505 if (p == PER_LINUX)
6506 return "x86";
6507#endif
6508
6509 return NULL;
6510}
1c231f56
LP
6511
6512uint64_t physical_memory(void) {
6513 long mem;
6514
6515 /* We return this as uint64_t in case we are running as 32bit
6516 * process on a 64bit kernel with huge amounts of memory */
6517
6518 mem = sysconf(_SC_PHYS_PAGES);
6519 assert(mem > 0);
6520
6521 return (uint64_t) mem * (uint64_t) page_size();
6522}
6db615c1
LP
6523
6524char* mount_test_option(const char *haystack, const char *needle) {
6525
6526 struct mntent me = {
6527 .mnt_opts = (char*) haystack
6528 };
6529
6530 assert(needle);
6531
6532 /* Like glibc's hasmntopt(), but works on a string, not a
6533 * struct mntent */
6534
6535 if (!haystack)
6536 return NULL;
6537
6538 return hasmntopt(&me, needle);
6539}
29bfbcd6
LP
6540
6541void hexdump(FILE *f, const void *p, size_t s) {
6542 const uint8_t *b = p;
6543 unsigned n = 0;
6544
6545 assert(s == 0 || b);
6546
6547 while (s > 0) {
6548 size_t i;
6549
6550 fprintf(f, "%04x ", n);
6551
6552 for (i = 0; i < 16; i++) {
6553
6554 if (i >= s)
6555 fputs(" ", f);
6556 else
6557 fprintf(f, "%02x ", b[i]);
6558
6559 if (i == 7)
6560 fputc(' ', f);
6561 }
6562
6563 fputc(' ', f);
6564
6565 for (i = 0; i < 16; i++) {
6566
6567 if (i >= s)
6568 fputc(' ', f);
6569 else
6570 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
6571 }
6572
6573 fputc('\n', f);
6574
6575 if (s < 16)
6576 break;
6577
6578 n += 16;
6579 b += 16;
6580 s -= 16;
6581 }
6582}
c5220a94 6583
966bff26 6584int update_reboot_param_file(const char *param) {
c5220a94
MO
6585 int r = 0;
6586
6587 if (param) {
6588
6589 r = write_string_file(REBOOT_PARAM_FILE, param);
6590 if (r < 0)
6591 log_error("Failed to write reboot param to "
6592 REBOOT_PARAM_FILE": %s", strerror(-r));
6593 } else
6594 unlink(REBOOT_PARAM_FILE);
6595
6596 return r;
6597}
6d313367
LP
6598
6599int umount_recursive(const char *prefix, int flags) {
6600 bool again;
6601 int n = 0, r;
6602
6603 /* Try to umount everything recursively below a
6604 * directory. Also, take care of stacked mounts, and keep
6605 * unmounting them until they are gone. */
6606
6607 do {
6608 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6609
6610 again = false;
6611 r = 0;
6612
6613 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6614 if (!proc_self_mountinfo)
6615 return -errno;
6616
6617 for (;;) {
6618 _cleanup_free_ char *path = NULL, *p = NULL;
6619 int k;
6620
6621 k = fscanf(proc_self_mountinfo,
6622 "%*s " /* (1) mount id */
6623 "%*s " /* (2) parent id */
6624 "%*s " /* (3) major:minor */
6625 "%*s " /* (4) root */
6626 "%ms " /* (5) mount point */
6627 "%*s" /* (6) mount options */
6628 "%*[^-]" /* (7) optional fields */
6629 "- " /* (8) separator */
6630 "%*s " /* (9) file system type */
6631 "%*s" /* (10) mount source */
6632 "%*s" /* (11) mount options 2 */
6633 "%*[^\n]", /* some rubbish at the end */
6634 &path);
6d313367
LP
6635 if (k != 1) {
6636 if (k == EOF)
6637 break;
6638
6639 continue;
6640 }
6641
6642 p = cunescape(path);
6643 if (!p)
6644 return -ENOMEM;
6645
6646 if (!path_startswith(p, prefix))
6647 continue;
6648
6649 if (umount2(p, flags) < 0) {
6650 r = -errno;
6651 continue;
6652 }
6653
6654 again = true;
6655 n++;
6656
6657 break;
6658 }
6659
6660 } while (again);
6661
6662 return r ? r : n;
6663}
d6797c92
LP
6664
6665int bind_remount_recursive(const char *prefix, bool ro) {
6666 _cleanup_set_free_free_ Set *done = NULL;
6667 _cleanup_free_ char *cleaned = NULL;
6668 int r;
6669
6670 /* Recursively remount a directory (and all its submounts)
6671 * read-only or read-write. If the directory is already
6672 * mounted, we reuse the mount and simply mark it
6673 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6674 * operation). If it isn't we first make it one. Afterwards we
6675 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6676 * submounts we can access, too. When mounts are stacked on
6677 * the same mount point we only care for each individual
6678 * "top-level" mount on each point, as we cannot
6679 * influence/access the underlying mounts anyway. We do not
6680 * have any effect on future submounts that might get
6681 * propagated, they migt be writable. This includes future
6682 * submounts that have been triggered via autofs. */
6683
6684 cleaned = strdup(prefix);
6685 if (!cleaned)
6686 return -ENOMEM;
6687
6688 path_kill_slashes(cleaned);
6689
6690 done = set_new(string_hash_func, string_compare_func);
6691 if (!done)
6692 return -ENOMEM;
6693
6694 for (;;) {
6695 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6696 _cleanup_set_free_free_ Set *todo = NULL;
6697 bool top_autofs = false;
6698 char *x;
6699
6700 todo = set_new(string_hash_func, string_compare_func);
6701 if (!todo)
6702 return -ENOMEM;
6703
6704 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6705 if (!proc_self_mountinfo)
6706 return -errno;
6707
6708 for (;;) {
6709 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
6710 int k;
6711
6712 k = fscanf(proc_self_mountinfo,
6713 "%*s " /* (1) mount id */
6714 "%*s " /* (2) parent id */
6715 "%*s " /* (3) major:minor */
6716 "%*s " /* (4) root */
6717 "%ms " /* (5) mount point */
6718 "%*s" /* (6) mount options (superblock) */
6719 "%*[^-]" /* (7) optional fields */
6720 "- " /* (8) separator */
6721 "%ms " /* (9) file system type */
6722 "%*s" /* (10) mount source */
6723 "%*s" /* (11) mount options (bind mount) */
6724 "%*[^\n]", /* some rubbish at the end */
6725 &path,
6726 &type);
6727 if (k != 2) {
6728 if (k == EOF)
6729 break;
6730
6731 continue;
6732 }
6733
6734 p = cunescape(path);
6735 if (!p)
6736 return -ENOMEM;
6737
6738 /* Let's ignore autofs mounts. If they aren't
6739 * triggered yet, we want to avoid triggering
6740 * them, as we don't make any guarantees for
6741 * future submounts anyway. If they are
6742 * already triggered, then we will find
6743 * another entry for this. */
6744 if (streq(type, "autofs")) {
6745 top_autofs = top_autofs || path_equal(cleaned, p);
6746 continue;
6747 }
6748
6749 if (path_startswith(p, cleaned) &&
6750 !set_contains(done, p)) {
6751
6752 r = set_consume(todo, p);
6753 p = NULL;
6754
6755 if (r == -EEXIST)
6756 continue;
6757 if (r < 0)
6758 return r;
6759 }
6760 }
6761
6762 /* If we have no submounts to process anymore and if
6763 * the root is either already done, or an autofs, we
6764 * are done */
6765 if (set_isempty(todo) &&
6766 (top_autofs || set_contains(done, cleaned)))
6767 return 0;
6768
6769 if (!set_contains(done, cleaned) &&
6770 !set_contains(todo, cleaned)) {
6771 /* The prefix directory itself is not yet a
6772 * mount, make it one. */
6773 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
6774 return -errno;
6775
6776 if (mount(NULL, prefix, NULL, MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
6777 return -errno;
6778
6779 x = strdup(cleaned);
6780 if (!x)
6781 return -ENOMEM;
6782
6783 r = set_consume(done, x);
6784 if (r < 0)
6785 return r;
6786 }
6787
6788 while ((x = set_steal_first(todo))) {
6789
6790 r = set_consume(done, x);
6791 if (r == -EEXIST)
6792 continue;
6793 if (r < 0)
6794 return r;
6795
6796 if (mount(NULL, x, NULL, MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
6797
6798 /* Deal with mount points that are
6799 * obstructed by a later mount */
6800
6801 if (errno != ENOENT)
6802 return -errno;
6803 }
6804
6805 }
6806 }
6807}
1b992147
LP
6808
6809int fflush_and_check(FILE *f) {
45c196a7 6810 assert(f);
1b992147
LP
6811
6812 errno = 0;
6813 fflush(f);
6814
6815 if (ferror(f))
6816 return errno ? -errno : -EIO;
6817
6818 return 0;
6819}
2e78fa79
LP
6820
6821char *tempfn_xxxxxx(const char *p) {
6822 const char *fn;
6823 char *t;
6824 size_t k;
6825
6826 assert(p);
6827
6828 t = new(char, strlen(p) + 1 + 6 + 1);
6829 if (!t)
6830 return NULL;
6831
6832 fn = basename(p);
6833 k = fn - p;
6834
6835 strcpy(stpcpy(stpcpy(mempcpy(t, p, k), "."), fn), "XXXXXX");
6836
6837 return t;
6838}
6839
6840char *tempfn_random(const char *p) {
6841 const char *fn;
6842 char *t, *x;
6843 uint64_t u;
6844 size_t k;
6845 unsigned i;
6846
6847 assert(p);
6848
6849 t = new(char, strlen(p) + 1 + 16 + 1);
6850 if (!t)
6851 return NULL;
6852
6853 fn = basename(p);
6854 k = fn - p;
6855
6856 x = stpcpy(stpcpy(mempcpy(t, p, k), "."), fn);
6857
6858 u = random_u64();
6859 for (i = 0; i < 16; i++) {
6860 *(x++) = hexchar(u & 0xF);
6861 u >>= 4;
6862 }
6863
6864 *x = 0;
6865
6866 return t;
6867}
fecc80c1
LP
6868
6869/* make sure the hostname is not "localhost" */
6870bool is_localhost(const char *hostname) {
6871 assert(hostname);
6872
a0627f82
LP
6873 /* This tries to identify local host and domain names
6874 * described in RFC6761 plus the redhatism of .localdomain */
fecc80c1
LP
6875
6876 return streq(hostname, "localhost") ||
6877 streq(hostname, "localhost.") ||
a0627f82
LP
6878 streq(hostname, "localdomain.") ||
6879 streq(hostname, "localdomain") ||
fecc80c1
LP
6880 endswith(hostname, ".localhost") ||
6881 endswith(hostname, ".localhost.") ||
6882 endswith(hostname, ".localdomain") ||
6883 endswith(hostname, ".localdomain.");
6884}
45035609
LP
6885
6886int take_password_lock(const char *root) {
6887
6888 struct flock flock = {
6889 .l_type = F_WRLCK,
6890 .l_whence = SEEK_SET,
6891 .l_start = 0,
6892 .l_len = 0,
6893 };
6894
6895 const char *path;
6896 int fd, r;
6897
6898 /* This is roughly the same as lckpwdf(), but not as awful. We
6899 * don't want to use alarm() and signals, hence we implement
6900 * our own trivial version of this.
6901 *
6902 * Note that shadow-utils also takes per-database locks in
6903 * addition to lckpwdf(). However, we don't given that they
6904 * are redundant as they they invoke lckpwdf() first and keep
6905 * it during everything they do. The per-database locks are
6906 * awfully racy, and thus we just won't do them. */
6907
6908 if (root)
6909 path = strappenda(root, "/etc/.pwd.lock");
6910 else
6911 path = "/etc/.pwd.lock";
6912
6913 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
6914 if (fd < 0)
6915 return -errno;
6916
6917 r = fcntl(fd, F_SETLKW, &flock);
6918 if (r < 0) {
6919 safe_close(fd);
6920 return -errno;
6921 }
6922
6923 return fd;
6924}
5261ba90
TT
6925
6926int is_symlink(const char *path) {
6927 struct stat info;
6928
6929 if (lstat(path, &info) < 0)
6930 return -errno;
6931
6932 if (S_ISLNK(info.st_mode))
6933 return 1;
6934
6935 return 0;
a0627f82 6936}