]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/util.c
journal-remote: remove unreachable code
[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
aa62a893 3945 log_debug("Spawned %s as " PID_FMT ".", path, pid);
83cc030f 3946
aa62a893
LP
3947 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
3948 if (r < 0) {
3949 log_oom();
3950 _exit(EXIT_FAILURE);
3951 }
3952
3953 path = NULL;
83cc030f
LP
3954 }
3955
aa62a893
LP
3956 /* Abort execution of this process after the
3957 * timout. We simply rely on SIGALRM as default action
3958 * terminating the process, and turn on alarm(). */
3959
3a43da28 3960 if (timeout != USEC_INFINITY)
aa62a893
LP
3961 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
3962
3963 while (!hashmap_isempty(pids)) {
3964 _cleanup_free_ char *path = NULL;
3965 pid_t pid;
3966
3967 pid = PTR_TO_UINT(hashmap_first_key(pids));
3968 assert(pid > 0);
83cc030f 3969
aa62a893
LP
3970 path = hashmap_remove(pids, UINT_TO_PTR(pid));
3971 assert(path);
3972
3973 wait_for_terminate_and_warn(path, pid);
83cc030f 3974 }
83cc030f 3975
aa62a893
LP
3976 _exit(EXIT_SUCCESS);
3977 }
83cc030f 3978
aa62a893 3979 wait_for_terminate_and_warn(directory, executor_pid);
83cc030f
LP
3980}
3981
430c18ed
LP
3982int kill_and_sigcont(pid_t pid, int sig) {
3983 int r;
3984
3985 r = kill(pid, sig) < 0 ? -errno : 0;
3986
3987 if (r >= 0)
3988 kill(pid, SIGCONT);
3989
3990 return r;
3991}
3992
05feefe0
LP
3993bool nulstr_contains(const char*nulstr, const char *needle) {
3994 const char *i;
3995
3996 if (!nulstr)
3997 return false;
3998
3999 NULSTR_FOREACH(i, nulstr)
4000 if (streq(i, needle))
4001 return true;
4002
4003 return false;
4004}
4005
6faa1114 4006bool plymouth_running(void) {
9408a2d2 4007 return access("/run/plymouth/pid", F_OK) >= 0;
6faa1114
LP
4008}
4009
9beb3f4d
LP
4010char* strshorten(char *s, size_t l) {
4011 assert(s);
4012
4013 if (l < strlen(s))
4014 s[l] = 0;
4015
4016 return s;
4017}
4018
4019static bool hostname_valid_char(char c) {
4020 return
4021 (c >= 'a' && c <= 'z') ||
4022 (c >= 'A' && c <= 'Z') ||
4023 (c >= '0' && c <= '9') ||
4024 c == '-' ||
4025 c == '_' ||
4026 c == '.';
4027}
4028
4029bool hostname_is_valid(const char *s) {
4030 const char *p;
aa3c5cf8 4031 bool dot;
9beb3f4d
LP
4032
4033 if (isempty(s))
4034 return false;
4035
aa3c5cf8
LP
4036 for (p = s, dot = true; *p; p++) {
4037 if (*p == '.') {
4038 if (dot)
4039 return false;
4040
4041 dot = true;
4042 } else {
4043 if (!hostname_valid_char(*p))
4044 return false;
4045
4046 dot = false;
4047 }
4048 }
4049
4050 if (dot)
4051 return false;
9beb3f4d
LP
4052
4053 if (p-s > HOST_NAME_MAX)
4054 return false;
4055
4056 return true;
4057}
4058
e724b063 4059char* hostname_cleanup(char *s, bool lowercase) {
9beb3f4d 4060 char *p, *d;
cec4ead9
LP
4061 bool dot;
4062
4063 for (p = s, d = s, dot = true; *p; p++) {
4064 if (*p == '.') {
e724b063 4065 if (dot)
cec4ead9 4066 continue;
9beb3f4d 4067
e724b063 4068 *(d++) = '.';
cec4ead9 4069 dot = true;
e724b063
LP
4070 } else if (hostname_valid_char(*p)) {
4071 *(d++) = lowercase ? tolower(*p) : *p;
cec4ead9 4072 dot = false;
e724b063 4073 }
cec4ead9 4074
cec4ead9 4075 }
9beb3f4d 4076
e724b063
LP
4077 if (dot && d > s)
4078 d[-1] = 0;
4079 else
4080 *d = 0;
4081
9beb3f4d 4082 strshorten(s, HOST_NAME_MAX);
cec4ead9 4083
9beb3f4d
LP
4084 return s;
4085}
4086
7f0d207d
LP
4087bool machine_name_is_valid(const char *s) {
4088
4089 if (!hostname_is_valid(s))
4090 return false;
4091
4092 /* Machine names should be useful hostnames, but also be
4093 * useful in unit names, hence we enforce a stricter length
4094 * limitation. */
4095
4096 if (strlen(s) > 64)
4097 return false;
4098
4099 return true;
4100}
4101
1325aa42 4102int pipe_eof(int fd) {
b92bea5d
ZJS
4103 struct pollfd pollfd = {
4104 .fd = fd,
4105 .events = POLLIN|POLLHUP,
4106 };
1325aa42 4107
d37a91e8
LP
4108 int r;
4109
1325aa42
LP
4110 r = poll(&pollfd, 1, 0);
4111 if (r < 0)
4112 return -errno;
4113
4114 if (r == 0)
4115 return 0;
4116
4117 return pollfd.revents & POLLHUP;
4118}
4119
8f2d43a0 4120int fd_wait_for_event(int fd, int event, usec_t t) {
968d3d24 4121
b92bea5d
ZJS
4122 struct pollfd pollfd = {
4123 .fd = fd,
4124 .events = event,
4125 };
df50185b 4126
968d3d24
LP
4127 struct timespec ts;
4128 int r;
4129
3a43da28 4130 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
df50185b
LP
4131 if (r < 0)
4132 return -errno;
4133
4134 if (r == 0)
4135 return 0;
4136
4137 return pollfd.revents;
4138}
4139
5a3ab509
LP
4140int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4141 FILE *f;
4142 char *t;
5a3ab509
LP
4143 int fd;
4144
4145 assert(path);
4146 assert(_f);
4147 assert(_temp_path);
4148
2e78fa79 4149 t = tempfn_xxxxxx(path);
5a3ab509
LP
4150 if (!t)
4151 return -ENOMEM;
4152
2d5bdf5b 4153 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
5a3ab509
LP
4154 if (fd < 0) {
4155 free(t);
4156 return -errno;
4157 }
4158
4159 f = fdopen(fd, "we");
4160 if (!f) {
4161 unlink(t);
4162 free(t);
4163 return -errno;
4164 }
4165
4166 *_f = f;
4167 *_temp_path = t;
4168
4169 return 0;
4170}
4171
6ea832a2 4172int terminal_vhangup_fd(int fd) {
5a3ab509
LP
4173 assert(fd >= 0);
4174
6ea832a2
LP
4175 if (ioctl(fd, TIOCVHANGUP) < 0)
4176 return -errno;
4177
4178 return 0;
4179}
4180
4181int terminal_vhangup(const char *name) {
03e334a1 4182 _cleanup_close_ int fd;
6ea832a2
LP
4183
4184 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4185 if (fd < 0)
4186 return fd;
4187
03e334a1 4188 return terminal_vhangup_fd(fd);
6ea832a2
LP
4189}
4190
4191int vt_disallocate(const char *name) {
4192 int fd, r;
4193 unsigned u;
6ea832a2
LP
4194
4195 /* Deallocate the VT if possible. If not possible
4196 * (i.e. because it is the active one), at least clear it
4197 * entirely (including the scrollback buffer) */
4198
b83bc4e9
LP
4199 if (!startswith(name, "/dev/"))
4200 return -EINVAL;
4201
4202 if (!tty_is_vc(name)) {
4203 /* So this is not a VT. I guess we cannot deallocate
4204 * it then. But let's at least clear the screen */
4205
4206 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4207 if (fd < 0)
4208 return fd;
4209
8585357a
LP
4210 loop_write(fd,
4211 "\033[r" /* clear scrolling region */
4212 "\033[H" /* move home */
4213 "\033[2J", /* clear screen */
4214 10, false);
03e334a1 4215 safe_close(fd);
b83bc4e9
LP
4216
4217 return 0;
4218 }
6ea832a2
LP
4219
4220 if (!startswith(name, "/dev/tty"))
4221 return -EINVAL;
4222
4223 r = safe_atou(name+8, &u);
4224 if (r < 0)
4225 return r;
4226
4227 if (u <= 0)
b83bc4e9 4228 return -EINVAL;
6ea832a2 4229
b83bc4e9 4230 /* Try to deallocate */
6ea832a2
LP
4231 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4232 if (fd < 0)
4233 return fd;
4234
4235 r = ioctl(fd, VT_DISALLOCATE, u);
03e334a1 4236 safe_close(fd);
6ea832a2 4237
b83bc4e9
LP
4238 if (r >= 0)
4239 return 0;
6ea832a2 4240
b83bc4e9 4241 if (errno != EBUSY)
6ea832a2 4242 return -errno;
6ea832a2 4243
b83bc4e9
LP
4244 /* Couldn't deallocate, so let's clear it fully with
4245 * scrollback */
4246 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
6ea832a2 4247 if (fd < 0)
b83bc4e9 4248 return fd;
6ea832a2 4249
8585357a
LP
4250 loop_write(fd,
4251 "\033[r" /* clear scrolling region */
4252 "\033[H" /* move home */
4253 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4254 10, false);
03e334a1 4255 safe_close(fd);
6ea832a2 4256
b83bc4e9 4257 return 0;
6ea832a2
LP
4258}
4259
424a19f8 4260int symlink_atomic(const char *from, const char *to) {
2e78fa79 4261 _cleanup_free_ char *t = NULL;
34ca941c
LP
4262
4263 assert(from);
4264 assert(to);
4265
2e78fa79 4266 t = tempfn_random(to);
34ca941c
LP
4267 if (!t)
4268 return -ENOMEM;
4269
424a19f8
LP
4270 if (symlink(from, t) < 0)
4271 return -errno;
34ca941c
LP
4272
4273 if (rename(t, to) < 0) {
2e78fa79
LP
4274 unlink_noerrno(t);
4275 return -errno;
34ca941c
LP
4276 }
4277
424a19f8 4278 return 0;
34ca941c
LP
4279}
4280
1554afae
LP
4281int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
4282 _cleanup_free_ char *t = NULL;
4283
4284 assert(path);
4285
4286 t = tempfn_random(path);
4287 if (!t)
4288 return -ENOMEM;
4289
4290 if (mknod(t, mode, dev) < 0)
4291 return -errno;
4292
4293 if (rename(t, path) < 0) {
4294 unlink_noerrno(t);
4295 return -errno;
4296 }
4297
4298 return 0;
4299}
4300
4301int mkfifo_atomic(const char *path, mode_t mode) {
4302 _cleanup_free_ char *t = NULL;
4303
4304 assert(path);
4305
4306 t = tempfn_random(path);
4307 if (!t)
4308 return -ENOMEM;
4309
4310 if (mkfifo(t, mode) < 0)
4311 return -errno;
4312
4313 if (rename(t, path) < 0) {
4314 unlink_noerrno(t);
4315 return -errno;
4316 }
4317
4318 return 0;
4319}
4320
4d6d6518
LP
4321bool display_is_local(const char *display) {
4322 assert(display);
4323
4324 return
4325 display[0] == ':' &&
4326 display[1] >= '0' &&
4327 display[1] <= '9';
4328}
4329
4330int socket_from_display(const char *display, char **path) {
4331 size_t k;
4332 char *f, *c;
4333
4334 assert(display);
4335 assert(path);
4336
4337 if (!display_is_local(display))
4338 return -EINVAL;
4339
4340 k = strspn(display+1, "0123456789");
4341
f8294e41 4342 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
4d6d6518
LP
4343 if (!f)
4344 return -ENOMEM;
4345
4346 c = stpcpy(f, "/tmp/.X11-unix/X");
4347 memcpy(c, display+1, k);
4348 c[k] = 0;
4349
4350 *path = f;
4351
4352 return 0;
4353}
4354
d05c5031
LP
4355int get_user_creds(
4356 const char **username,
4357 uid_t *uid, gid_t *gid,
4358 const char **home,
4359 const char **shell) {
4360
1cccf435 4361 struct passwd *p;
ddd88763 4362 uid_t u;
1cccf435
MV
4363
4364 assert(username);
4365 assert(*username);
1cccf435
MV
4366
4367 /* We enforce some special rules for uid=0: in order to avoid
4368 * NSS lookups for root we hardcode its data. */
4369
4370 if (streq(*username, "root") || streq(*username, "0")) {
4371 *username = "root";
4b67834e
LP
4372
4373 if (uid)
4374 *uid = 0;
4375
4376 if (gid)
4377 *gid = 0;
4378
4379 if (home)
4380 *home = "/root";
d05c5031
LP
4381
4382 if (shell)
4383 *shell = "/bin/sh";
4384
1cccf435
MV
4385 return 0;
4386 }
4387
ddd88763 4388 if (parse_uid(*username, &u) >= 0) {
1cccf435 4389 errno = 0;
ddd88763 4390 p = getpwuid(u);
1cccf435
MV
4391
4392 /* If there are multiple users with the same id, make
4393 * sure to leave $USER to the configured value instead
4394 * of the first occurrence in the database. However if
4395 * the uid was configured by a numeric uid, then let's
4396 * pick the real username from /etc/passwd. */
4397 if (p)
4398 *username = p->pw_name;
4399 } else {
4400 errno = 0;
4401 p = getpwnam(*username);
4402 }
4403
4404 if (!p)
8333c77e 4405 return errno > 0 ? -errno : -ESRCH;
1cccf435 4406
4b67834e
LP
4407 if (uid)
4408 *uid = p->pw_uid;
4409
4410 if (gid)
4411 *gid = p->pw_gid;
4412
4413 if (home)
4414 *home = p->pw_dir;
4415
d05c5031
LP
4416 if (shell)
4417 *shell = p->pw_shell;
4418
4b67834e
LP
4419 return 0;
4420}
4421
59164be4
LP
4422char* uid_to_name(uid_t uid) {
4423 struct passwd *p;
4424 char *r;
4425
4426 if (uid == 0)
4427 return strdup("root");
4428
4429 p = getpwuid(uid);
4430 if (p)
4431 return strdup(p->pw_name);
4432
de0671ee 4433 if (asprintf(&r, UID_FMT, uid) < 0)
59164be4
LP
4434 return NULL;
4435
4436 return r;
4437}
4438
4468addc
LP
4439char* gid_to_name(gid_t gid) {
4440 struct group *p;
4441 char *r;
4442
4443 if (gid == 0)
4444 return strdup("root");
4445
4446 p = getgrgid(gid);
4447 if (p)
4448 return strdup(p->gr_name);
4449
de0671ee 4450 if (asprintf(&r, GID_FMT, gid) < 0)
4468addc
LP
4451 return NULL;
4452
4453 return r;
4454}
4455
4b67834e
LP
4456int get_group_creds(const char **groupname, gid_t *gid) {
4457 struct group *g;
4458 gid_t id;
4459
4460 assert(groupname);
4461
4462 /* We enforce some special rules for gid=0: in order to avoid
4463 * NSS lookups for root we hardcode its data. */
4464
4465 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4466 *groupname = "root";
4467
4468 if (gid)
4469 *gid = 0;
4470
4471 return 0;
4472 }
4473
4474 if (parse_gid(*groupname, &id) >= 0) {
4475 errno = 0;
4476 g = getgrgid(id);
4477
4478 if (g)
4479 *groupname = g->gr_name;
4480 } else {
4481 errno = 0;
4482 g = getgrnam(*groupname);
4483 }
4484
4485 if (!g)
8333c77e 4486 return errno > 0 ? -errno : -ESRCH;
4b67834e
LP
4487
4488 if (gid)
4489 *gid = g->gr_gid;
4490
1cccf435
MV
4491 return 0;
4492}
4493
4468addc
LP
4494int in_gid(gid_t gid) {
4495 gid_t *gids;
43673799
LP
4496 int ngroups_max, r, i;
4497
43673799
LP
4498 if (getgid() == gid)
4499 return 1;
4500
4501 if (getegid() == gid)
4502 return 1;
4503
4504 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4505 assert(ngroups_max > 0);
4506
4507 gids = alloca(sizeof(gid_t) * ngroups_max);
4508
4509 r = getgroups(ngroups_max, gids);
4510 if (r < 0)
4511 return -errno;
4512
4513 for (i = 0; i < r; i++)
4514 if (gids[i] == gid)
4515 return 1;
4516
4517 return 0;
4518}
4519
4468addc
LP
4520int in_group(const char *name) {
4521 int r;
4522 gid_t gid;
4523
4524 r = get_group_creds(&name, &gid);
4525 if (r < 0)
4526 return r;
4527
4528 return in_gid(gid);
4529}
4530
8092a428 4531int glob_exists(const char *path) {
7fd1b19b 4532 _cleanup_globfree_ glob_t g = {};
8d98da3f 4533 int k;
8092a428
LP
4534
4535 assert(path);
4536
8092a428
LP
4537 errno = 0;
4538 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4539
4540 if (k == GLOB_NOMATCH)
8d98da3f 4541 return 0;
8092a428 4542 else if (k == GLOB_NOSPACE)
8d98da3f 4543 return -ENOMEM;
8092a428 4544 else if (k == 0)
8d98da3f 4545 return !strv_isempty(g.gl_pathv);
8092a428 4546 else
8d98da3f
ZJS
4547 return errno ? -errno : -EIO;
4548}
8092a428 4549
8d98da3f
ZJS
4550int glob_extend(char ***strv, const char *path) {
4551 _cleanup_globfree_ glob_t g = {};
4552 int k;
4553 char **p;
4554
4555 errno = 0;
a8ccacf5 4556 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
8d98da3f
ZJS
4557
4558 if (k == GLOB_NOMATCH)
4559 return -ENOENT;
4560 else if (k == GLOB_NOSPACE)
4561 return -ENOMEM;
4562 else if (k != 0 || strv_isempty(g.gl_pathv))
4563 return errno ? -errno : -EIO;
4564
4565 STRV_FOREACH(p, g.gl_pathv) {
4566 k = strv_extend(strv, *p);
4567 if (k < 0)
4568 break;
4569 }
4570
4571 return k;
8092a428
LP
4572}
4573
83096483
LP
4574int dirent_ensure_type(DIR *d, struct dirent *de) {
4575 struct stat st;
4576
4577 assert(d);
4578 assert(de);
4579
4580 if (de->d_type != DT_UNKNOWN)
4581 return 0;
4582
4583 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4584 return -errno;
4585
4586 de->d_type =
4587 S_ISREG(st.st_mode) ? DT_REG :
4588 S_ISDIR(st.st_mode) ? DT_DIR :
4589 S_ISLNK(st.st_mode) ? DT_LNK :
4590 S_ISFIFO(st.st_mode) ? DT_FIFO :
4591 S_ISSOCK(st.st_mode) ? DT_SOCK :
4592 S_ISCHR(st.st_mode) ? DT_CHR :
4593 S_ISBLK(st.st_mode) ? DT_BLK :
4594 DT_UNKNOWN;
4595
4596 return 0;
4597}
4598
034a2a52 4599int get_files_in_directory(const char *path, char ***list) {
893fa014
ZJS
4600 _cleanup_closedir_ DIR *d = NULL;
4601 size_t bufsize = 0, n = 0;
4602 _cleanup_strv_free_ char **l = NULL;
034a2a52
LP
4603
4604 assert(path);
d60ef526
LP
4605
4606 /* Returns all files in a directory in *list, and the number
4607 * of files as return value. If list is NULL returns only the
893fa014 4608 * number. */
034a2a52
LP
4609
4610 d = opendir(path);
8ea913b2
LP
4611 if (!d)
4612 return -errno;
4613
034a2a52 4614 for (;;) {
7d5e9c0f 4615 struct dirent *de;
034a2a52 4616
3fd11280
FW
4617 errno = 0;
4618 de = readdir(d);
4619 if (!de && errno != 0)
4620 return -errno;
034a2a52
LP
4621 if (!de)
4622 break;
4623
4624 dirent_ensure_type(d, de);
4625
4626 if (!dirent_is_file(de))
4627 continue;
4628
d60ef526 4629 if (list) {
893fa014
ZJS
4630 /* one extra slot is needed for the terminating NULL */
4631 if (!GREEDY_REALLOC(l, bufsize, n + 2))
4632 return -ENOMEM;
034a2a52 4633
893fa014
ZJS
4634 l[n] = strdup(de->d_name);
4635 if (!l[n])
4636 return -ENOMEM;
034a2a52 4637
893fa014 4638 l[++n] = NULL;
d60ef526 4639 } else
893fa014 4640 n++;
034a2a52
LP
4641 }
4642
893fa014
ZJS
4643 if (list) {
4644 *list = l;
4645 l = NULL; /* avoid freeing */
4646 }
034a2a52 4647
893fa014 4648 return n;
034a2a52
LP
4649}
4650
b7def684 4651char *strjoin(const char *x, ...) {
911a4828
LP
4652 va_list ap;
4653 size_t l;
4654 char *r, *p;
4655
4656 va_start(ap, x);
4657
4658 if (x) {
4659 l = strlen(x);
4660
4661 for (;;) {
4662 const char *t;
040f18ea 4663 size_t n;
911a4828
LP
4664
4665 t = va_arg(ap, const char *);
4666 if (!t)
4667 break;
4668
040f18ea 4669 n = strlen(t);
e98055de
LN
4670 if (n > ((size_t) -1) - l) {
4671 va_end(ap);
040f18ea 4672 return NULL;
e98055de 4673 }
040f18ea
LP
4674
4675 l += n;
911a4828
LP
4676 }
4677 } else
4678 l = 0;
4679
4680 va_end(ap);
4681
4682 r = new(char, l+1);
4683 if (!r)
4684 return NULL;
4685
4686 if (x) {
4687 p = stpcpy(r, x);
4688
4689 va_start(ap, x);
4690
4691 for (;;) {
4692 const char *t;
4693
4694 t = va_arg(ap, const char *);
4695 if (!t)
4696 break;
4697
4698 p = stpcpy(p, t);
4699 }
8ea913b2
LP
4700
4701 va_end(ap);
911a4828
LP
4702 } else
4703 r[0] = 0;
4704
4705 return r;
4706}
4707
b636465b 4708bool is_main_thread(void) {
ec202eae 4709 static thread_local int cached = 0;
b636465b
LP
4710
4711 if (_unlikely_(cached == 0))
4712 cached = getpid() == gettid() ? 1 : -1;
4713
4714 return cached > 0;
4715}
4716
94959f0f
LP
4717int block_get_whole_disk(dev_t d, dev_t *ret) {
4718 char *p, *s;
4719 int r;
4720 unsigned n, m;
4721
4722 assert(ret);
4723
4724 /* If it has a queue this is good enough for us */
4725 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4726 return -ENOMEM;
4727
4728 r = access(p, F_OK);
4729 free(p);
4730
4731 if (r >= 0) {
4732 *ret = d;
4733 return 0;
4734 }
4735
4736 /* If it is a partition find the originating device */
4737 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4738 return -ENOMEM;
4739
4740 r = access(p, F_OK);
4741 free(p);
4742
4743 if (r < 0)
4744 return -ENOENT;
4745
4746 /* Get parent dev_t */
4747 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4748 return -ENOMEM;
4749
4750 r = read_one_line_file(p, &s);
4751 free(p);
4752
4753 if (r < 0)
4754 return r;
4755
4756 r = sscanf(s, "%u:%u", &m, &n);
4757 free(s);
4758
4759 if (r != 2)
4760 return -EINVAL;
4761
4762 /* Only return this if it is really good enough for us. */
4763 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4764 return -ENOMEM;
4765
4766 r = access(p, F_OK);
4767 free(p);
4768
4769 if (r >= 0) {
4770 *ret = makedev(m, n);
4771 return 0;
4772 }
4773
4774 return -ENOENT;
4775}
4776
8d53b453 4777int file_is_priv_sticky(const char *p) {
ad293f5a
LP
4778 struct stat st;
4779
4780 assert(p);
4781
4782 if (lstat(p, &st) < 0)
4783 return -errno;
4784
4785 return
8d53b453 4786 (st.st_uid == 0 || st.st_uid == getuid()) &&
ad293f5a
LP
4787 (st.st_mode & S_ISVTX);
4788}
94959f0f 4789
f41607a6
LP
4790static const char *const ioprio_class_table[] = {
4791 [IOPRIO_CLASS_NONE] = "none",
4792 [IOPRIO_CLASS_RT] = "realtime",
4793 [IOPRIO_CLASS_BE] = "best-effort",
4794 [IOPRIO_CLASS_IDLE] = "idle"
4795};
4796
f8b69d1d 4797DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
f41607a6
LP
4798
4799static const char *const sigchld_code_table[] = {
4800 [CLD_EXITED] = "exited",
4801 [CLD_KILLED] = "killed",
4802 [CLD_DUMPED] = "dumped",
4803 [CLD_TRAPPED] = "trapped",
4804 [CLD_STOPPED] = "stopped",
4805 [CLD_CONTINUED] = "continued",
4806};
4807
4808DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4809
4810static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4811 [LOG_FAC(LOG_KERN)] = "kern",
4812 [LOG_FAC(LOG_USER)] = "user",
4813 [LOG_FAC(LOG_MAIL)] = "mail",
4814 [LOG_FAC(LOG_DAEMON)] = "daemon",
4815 [LOG_FAC(LOG_AUTH)] = "auth",
4816 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4817 [LOG_FAC(LOG_LPR)] = "lpr",
4818 [LOG_FAC(LOG_NEWS)] = "news",
4819 [LOG_FAC(LOG_UUCP)] = "uucp",
4820 [LOG_FAC(LOG_CRON)] = "cron",
4821 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4822 [LOG_FAC(LOG_FTP)] = "ftp",
4823 [LOG_FAC(LOG_LOCAL0)] = "local0",
4824 [LOG_FAC(LOG_LOCAL1)] = "local1",
4825 [LOG_FAC(LOG_LOCAL2)] = "local2",
4826 [LOG_FAC(LOG_LOCAL3)] = "local3",
4827 [LOG_FAC(LOG_LOCAL4)] = "local4",
4828 [LOG_FAC(LOG_LOCAL5)] = "local5",
4829 [LOG_FAC(LOG_LOCAL6)] = "local6",
4830 [LOG_FAC(LOG_LOCAL7)] = "local7"
4831};
4832
f8b69d1d 4833DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
f41607a6
LP
4834
4835static const char *const log_level_table[] = {
4836 [LOG_EMERG] = "emerg",
4837 [LOG_ALERT] = "alert",
4838 [LOG_CRIT] = "crit",
4839 [LOG_ERR] = "err",
4840 [LOG_WARNING] = "warning",
4841 [LOG_NOTICE] = "notice",
4842 [LOG_INFO] = "info",
4843 [LOG_DEBUG] = "debug"
4844};
4845
f8b69d1d 4846DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
f41607a6
LP
4847
4848static const char* const sched_policy_table[] = {
4849 [SCHED_OTHER] = "other",
4850 [SCHED_BATCH] = "batch",
4851 [SCHED_IDLE] = "idle",
4852 [SCHED_FIFO] = "fifo",
4853 [SCHED_RR] = "rr"
4854};
4855
f8b69d1d 4856DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
f41607a6 4857
517d56b1 4858static const char* const rlimit_table[_RLIMIT_MAX] = {
f41607a6
LP
4859 [RLIMIT_CPU] = "LimitCPU",
4860 [RLIMIT_FSIZE] = "LimitFSIZE",
4861 [RLIMIT_DATA] = "LimitDATA",
4862 [RLIMIT_STACK] = "LimitSTACK",
4863 [RLIMIT_CORE] = "LimitCORE",
4864 [RLIMIT_RSS] = "LimitRSS",
4865 [RLIMIT_NOFILE] = "LimitNOFILE",
4866 [RLIMIT_AS] = "LimitAS",
4867 [RLIMIT_NPROC] = "LimitNPROC",
4868 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4869 [RLIMIT_LOCKS] = "LimitLOCKS",
4870 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4871 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4872 [RLIMIT_NICE] = "LimitNICE",
4873 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4874 [RLIMIT_RTTIME] = "LimitRTTIME"
4875};
4876
4877DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4878
4879static const char* const ip_tos_table[] = {
4880 [IPTOS_LOWDELAY] = "low-delay",
4881 [IPTOS_THROUGHPUT] = "throughput",
4882 [IPTOS_RELIABILITY] = "reliability",
4883 [IPTOS_LOWCOST] = "low-cost",
4884};
4885
f8b69d1d 4886DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
f41607a6 4887
4e240ab0 4888static const char *const __signal_table[] = {
f41607a6
LP
4889 [SIGHUP] = "HUP",
4890 [SIGINT] = "INT",
4891 [SIGQUIT] = "QUIT",
4892 [SIGILL] = "ILL",
4893 [SIGTRAP] = "TRAP",
4894 [SIGABRT] = "ABRT",
4895 [SIGBUS] = "BUS",
4896 [SIGFPE] = "FPE",
4897 [SIGKILL] = "KILL",
4898 [SIGUSR1] = "USR1",
4899 [SIGSEGV] = "SEGV",
4900 [SIGUSR2] = "USR2",
4901 [SIGPIPE] = "PIPE",
4902 [SIGALRM] = "ALRM",
4903 [SIGTERM] = "TERM",
4904#ifdef SIGSTKFLT
4905 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4906#endif
4907 [SIGCHLD] = "CHLD",
4908 [SIGCONT] = "CONT",
4909 [SIGSTOP] = "STOP",
4910 [SIGTSTP] = "TSTP",
4911 [SIGTTIN] = "TTIN",
4912 [SIGTTOU] = "TTOU",
4913 [SIGURG] = "URG",
4914 [SIGXCPU] = "XCPU",
4915 [SIGXFSZ] = "XFSZ",
4916 [SIGVTALRM] = "VTALRM",
4917 [SIGPROF] = "PROF",
4918 [SIGWINCH] = "WINCH",
4919 [SIGIO] = "IO",
4920 [SIGPWR] = "PWR",
4921 [SIGSYS] = "SYS"
4922};
4923
4e240ab0
MS
4924DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4925
4926const char *signal_to_string(int signo) {
ec202eae 4927 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4e240ab0
MS
4928 const char *name;
4929
4930 name = __signal_to_string(signo);
4931 if (name)
4932 return name;
4933
4934 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
fa70beaa 4935 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4e240ab0 4936 else
fa70beaa
LP
4937 snprintf(buf, sizeof(buf), "%d", signo);
4938
4e240ab0
MS
4939 return buf;
4940}
4941
4942int signal_from_string(const char *s) {
4943 int signo;
4944 int offset = 0;
4945 unsigned u;
4946
040f18ea 4947 signo = __signal_from_string(s);
4e240ab0
MS
4948 if (signo > 0)
4949 return signo;
4950
4951 if (startswith(s, "RTMIN+")) {
4952 s += 6;
4953 offset = SIGRTMIN;
4954 }
4955 if (safe_atou(s, &u) >= 0) {
4956 signo = (int) u + offset;
4957 if (signo > 0 && signo < _NSIG)
4958 return signo;
4959 }
7e8185ef 4960 return -EINVAL;
4e240ab0 4961}
65457142
FC
4962
4963bool kexec_loaded(void) {
4964 bool loaded = false;
4965 char *s;
4966
4967 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4968 if (s[0] == '1')
4969 loaded = true;
4970 free(s);
4971 }
4972 return loaded;
4973}
fb9de93d
LP
4974
4975int strdup_or_null(const char *a, char **b) {
4976 char *c;
4977
4978 assert(b);
4979
4980 if (!a) {
4981 *b = NULL;
4982 return 0;
4983 }
4984
4985 c = strdup(a);
4986 if (!c)
4987 return -ENOMEM;
4988
4989 *b = c;
4990 return 0;
4991}
64685e0c 4992
87d2c1ff
LP
4993int prot_from_flags(int flags) {
4994
4995 switch (flags & O_ACCMODE) {
4996
4997 case O_RDONLY:
4998 return PROT_READ;
4999
5000 case O_WRONLY:
5001 return PROT_WRITE;
5002
5003 case O_RDWR:
5004 return PROT_READ|PROT_WRITE;
5005
5006 default:
5007 return -EINVAL;
5008 }
7c99e0c1 5009}
689b9a22 5010
babfc091 5011char *format_bytes(char *buf, size_t l, off_t t) {
c0f99c21 5012 unsigned i;
babfc091
LP
5013
5014 static const struct {
5015 const char *suffix;
5016 off_t factor;
5017 } table[] = {
32895bb3
LP
5018 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5019 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
babfc091
LP
5020 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5021 { "G", 1024ULL*1024ULL*1024ULL },
5022 { "M", 1024ULL*1024ULL },
5023 { "K", 1024ULL },
5024 };
5025
5026 for (i = 0; i < ELEMENTSOF(table); i++) {
5027
5028 if (t >= table[i].factor) {
5029 snprintf(buf, l,
5030 "%llu.%llu%s",
5031 (unsigned long long) (t / table[i].factor),
5032 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5033 table[i].suffix);
5034
5035 goto finish;
5036 }
5037 }
5038
5039 snprintf(buf, l, "%lluB", (unsigned long long) t);
5040
5041finish:
5042 buf[l-1] = 0;
5043 return buf;
5044
5045}
55d7bfc1
LP
5046
5047void* memdup(const void *p, size_t l) {
5048 void *r;
5049
5050 assert(p);
5051
5052 r = malloc(l);
5053 if (!r)
5054 return NULL;
5055
5056 memcpy(r, p, l);
5057 return r;
5058}
bb99a35a
LP
5059
5060int fd_inc_sndbuf(int fd, size_t n) {
5061 int r, value;
5062 socklen_t l = sizeof(value);
5063
5064 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
92d75ca4 5065 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
bb99a35a
LP
5066 return 0;
5067
92d75ca4
LP
5068 /* If we have the privileges we will ignore the kernel limit. */
5069
bb99a35a 5070 value = (int) n;
92d75ca4
LP
5071 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
5072 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
5073 return -errno;
bb99a35a
LP
5074
5075 return 1;
5076}
5077
5078int fd_inc_rcvbuf(int fd, size_t n) {
5079 int r, value;
5080 socklen_t l = sizeof(value);
5081
5082 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
92d75ca4 5083 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
bb99a35a
LP
5084 return 0;
5085
92d75ca4 5086 /* If we have the privileges we will ignore the kernel limit. */
bb99a35a 5087
92d75ca4
LP
5088 value = (int) n;
5089 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
5090 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
5091 return -errno;
bb99a35a
LP
5092 return 1;
5093}
6bb92a16 5094
9bdc770c 5095int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
6bb92a16
LP
5096 pid_t parent_pid, agent_pid;
5097 int fd;
5098 bool stdout_is_tty, stderr_is_tty;
5099 unsigned n, i;
5100 va_list ap;
5101 char **l;
5102
5103 assert(pid);
5104 assert(path);
5105
5106 parent_pid = getpid();
5107
5108 /* Spawns a temporary TTY agent, making sure it goes away when
5109 * we go away */
5110
5111 agent_pid = fork();
5112 if (agent_pid < 0)
5113 return -errno;
5114
5115 if (agent_pid != 0) {
5116 *pid = agent_pid;
5117 return 0;
5118 }
5119
5120 /* In the child:
5121 *
5122 * Make sure the agent goes away when the parent dies */
5123 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5124 _exit(EXIT_FAILURE);
5125
5126 /* Check whether our parent died before we were able
5127 * to set the death signal */
5128 if (getppid() != parent_pid)
5129 _exit(EXIT_SUCCESS);
5130
5131 /* Don't leak fds to the agent */
9bdc770c 5132 close_all_fds(except, n_except);
6bb92a16
LP
5133
5134 stdout_is_tty = isatty(STDOUT_FILENO);
5135 stderr_is_tty = isatty(STDERR_FILENO);
5136
5137 if (!stdout_is_tty || !stderr_is_tty) {
5138 /* Detach from stdout/stderr. and reopen
5139 * /dev/tty for them. This is important to
5140 * ensure that when systemctl is started via
5141 * popen() or a similar call that expects to
5142 * read EOF we actually do generate EOF and
5143 * not delay this indefinitely by because we
5144 * keep an unused copy of stdin around. */
5145 fd = open("/dev/tty", O_WRONLY);
5146 if (fd < 0) {
5147 log_error("Failed to open /dev/tty: %m");
5148 _exit(EXIT_FAILURE);
5149 }
5150
5151 if (!stdout_is_tty)
5152 dup2(fd, STDOUT_FILENO);
5153
5154 if (!stderr_is_tty)
5155 dup2(fd, STDERR_FILENO);
5156
5157 if (fd > 2)
5158 close(fd);
5159 }
5160
5161 /* Count arguments */
5162 va_start(ap, path);
5163 for (n = 0; va_arg(ap, char*); n++)
5164 ;
5165 va_end(ap);
5166
5167 /* Allocate strv */
5168 l = alloca(sizeof(char *) * (n + 1));
5169
5170 /* Fill in arguments */
5171 va_start(ap, path);
5172 for (i = 0; i <= n; i++)
5173 l[i] = va_arg(ap, char*);
5174 va_end(ap);
5175
5176 execv(path, l);
5177 _exit(EXIT_FAILURE);
5178}
68faf98c
LP
5179
5180int setrlimit_closest(int resource, const struct rlimit *rlim) {
5181 struct rlimit highest, fixed;
5182
5183 assert(rlim);
5184
5185 if (setrlimit(resource, rlim) >= 0)
5186 return 0;
5187
5188 if (errno != EPERM)
5189 return -errno;
5190
5191 /* So we failed to set the desired setrlimit, then let's try
5192 * to get as close as we can */
5193 assert_se(getrlimit(resource, &highest) == 0);
5194
5195 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5196 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5197
5198 if (setrlimit(resource, &fixed) < 0)
5199 return -errno;
5200
5201 return 0;
5202}
3d9a4122 5203
ab94af92 5204int getenv_for_pid(pid_t pid, const char *field, char **_value) {
49aa47c7
LP
5205 _cleanup_fclose_ FILE *f = NULL;
5206 char *value = NULL;
ab94af92 5207 int r;
ab94af92
LP
5208 bool done = false;
5209 size_t l;
49aa47c7 5210 const char *path;
ab94af92 5211
49aa47c7 5212 assert(pid >= 0);
ab94af92
LP
5213 assert(field);
5214 assert(_value);
5215
b68fa010 5216 path = procfs_file_alloca(pid, "environ");
ab94af92
LP
5217
5218 f = fopen(path, "re");
5219 if (!f)
5220 return -errno;
5221
5222 l = strlen(field);
5223 r = 0;
5224
5225 do {
5226 char line[LINE_MAX];
5227 unsigned i;
5228
5229 for (i = 0; i < sizeof(line)-1; i++) {
5230 int c;
5231
5232 c = getc(f);
5233 if (_unlikely_(c == EOF)) {
5234 done = true;
5235 break;
5236 } else if (c == 0)
5237 break;
5238
5239 line[i] = c;
5240 }
5241 line[i] = 0;
5242
5243 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5244 value = strdup(line + l + 1);
49aa47c7
LP
5245 if (!value)
5246 return -ENOMEM;
ab94af92
LP
5247
5248 r = 1;
5249 break;
5250 }
5251
5252 } while (!done);
5253
49aa47c7 5254 *_value = value;
ab94af92
LP
5255 return r;
5256}
d889a206 5257
49dbfa7b
LP
5258bool is_valid_documentation_url(const char *url) {
5259 assert(url);
5260
5261 if (startswith(url, "http://") && url[7])
5262 return true;
5263
5264 if (startswith(url, "https://") && url[8])
5265 return true;
5266
5267 if (startswith(url, "file:") && url[5])
5268 return true;
5269
5270 if (startswith(url, "info:") && url[5])
5271 return true;
5272
5273 if (startswith(url, "man:") && url[4])
5274 return true;
5275
5276 return false;
5277}
9be346c9
HH
5278
5279bool in_initrd(void) {
73020ab2 5280 static int saved = -1;
825c6fe5 5281 struct statfs s;
8f33b5b8 5282
825c6fe5
LP
5283 if (saved >= 0)
5284 return saved;
5285
5286 /* We make two checks here:
5287 *
5288 * 1. the flag file /etc/initrd-release must exist
5289 * 2. the root file system must be a memory file system
5290 *
5291 * The second check is extra paranoia, since misdetecting an
5292 * initrd can have bad bad consequences due the initrd
5293 * emptying when transititioning to the main systemd.
5294 */
5295
5296 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5297 statfs("/", &s) >= 0 &&
943aad8c 5298 is_temporary_fs(&s);
9be346c9 5299
8f33b5b8 5300 return saved;
9be346c9 5301}
069cfc85
LP
5302
5303void warn_melody(void) {
e67f47e5 5304 _cleanup_close_ int fd = -1;
069cfc85
LP
5305
5306 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5307 if (fd < 0)
5308 return;
5309
040f18ea 5310 /* Yeah, this is synchronous. Kinda sucks. But well... */
069cfc85
LP
5311
5312 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5313 usleep(125*USEC_PER_MSEC);
5314
5315 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5316 usleep(125*USEC_PER_MSEC);
5317
5318 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5319 usleep(125*USEC_PER_MSEC);
5320
5321 ioctl(fd, KIOCSOUND, 0);
069cfc85 5322}
cd3bd60a
LP
5323
5324int make_console_stdio(void) {
5325 int fd, r;
5326
5327 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5328
3a43da28 5329 fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
cd3bd60a
LP
5330 if (fd < 0) {
5331 log_error("Failed to acquire terminal: %s", strerror(-fd));
5332 return fd;
5333 }
5334
5335 r = make_stdio(fd);
5336 if (r < 0) {
5337 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5338 return r;
5339 }
5340
5341 return 0;
5342}
7c5f152a
LP
5343
5344int get_home_dir(char **_h) {
2cfbd749 5345 struct passwd *p;
7c5f152a 5346 const char *e;
2cfbd749 5347 char *h;
7c5f152a 5348 uid_t u;
7c5f152a
LP
5349
5350 assert(_h);
5351
5352 /* Take the user specified one */
9a00f57a
LP
5353 e = secure_getenv("HOME");
5354 if (e && path_is_absolute(e)) {
7c5f152a
LP
5355 h = strdup(e);
5356 if (!h)
5357 return -ENOMEM;
5358
5359 *_h = h;
5360 return 0;
5361 }
5362
5363 /* Hardcode home directory for root to avoid NSS */
5364 u = getuid();
5365 if (u == 0) {
5366 h = strdup("/root");
5367 if (!h)
5368 return -ENOMEM;
5369
5370 *_h = h;
5371 return 0;
5372 }
5373
5374 /* Check the database... */
5375 errno = 0;
5376 p = getpwuid(u);
5377 if (!p)
bcb161b0 5378 return errno > 0 ? -errno : -ESRCH;
7c5f152a
LP
5379
5380 if (!path_is_absolute(p->pw_dir))
5381 return -EINVAL;
5382
5383 h = strdup(p->pw_dir);
5384 if (!h)
5385 return -ENOMEM;
5386
5387 *_h = h;
5388 return 0;
5389}
5390
2cfbd749
LP
5391int get_shell(char **_s) {
5392 struct passwd *p;
5393 const char *e;
5394 char *s;
5395 uid_t u;
5396
5397 assert(_s);
5398
5399 /* Take the user specified one */
5400 e = getenv("SHELL");
5401 if (e) {
5402 s = strdup(e);
5403 if (!s)
5404 return -ENOMEM;
5405
5406 *_s = s;
5407 return 0;
5408 }
5409
5410 /* Hardcode home directory for root to avoid NSS */
5411 u = getuid();
5412 if (u == 0) {
5413 s = strdup("/bin/sh");
5414 if (!s)
5415 return -ENOMEM;
5416
5417 *_s = s;
5418 return 0;
5419 }
5420
5421 /* Check the database... */
5422 errno = 0;
5423 p = getpwuid(u);
5424 if (!p)
5425 return errno > 0 ? -errno : -ESRCH;
5426
5427 if (!path_is_absolute(p->pw_shell))
5428 return -EINVAL;
5429
5430 s = strdup(p->pw_shell);
5431 if (!s)
5432 return -ENOMEM;
5433
5434 *_s = s;
5435 return 0;
5436}
5437
0b507b17
LP
5438bool filename_is_safe(const char *p) {
5439
5440 if (isempty(p))
5441 return false;
5442
5443 if (strchr(p, '/'))
5444 return false;
5445
5446 if (streq(p, "."))
5447 return false;
5448
5449 if (streq(p, ".."))
5450 return false;
5451
5452 if (strlen(p) > FILENAME_MAX)
5453 return false;
5454
5455 return true;
5456}
5457
5458bool string_is_safe(const char *p) {
5459 const char *t;
5460
6294aa76
LP
5461 if (!p)
5462 return false;
0b507b17
LP
5463
5464 for (t = p; *t; t++) {
01539d6e 5465 if (*t > 0 && *t < ' ')
0b507b17
LP
5466 return false;
5467
6294aa76 5468 if (strchr("\\\"\'\0x7f", *t))
0b507b17
LP
5469 return false;
5470 }
5471
5472 return true;
5473}
cfbc22ab 5474
ac4c8d6d 5475/**
6294aa76
LP
5476 * Check if a string contains control characters. If 'ok' is non-NULL
5477 * it may be a string containing additional CCs to be considered OK.
ac4c8d6d 5478 */
6294aa76 5479bool string_has_cc(const char *p, const char *ok) {
4d1a6904
LP
5480 const char *t;
5481
5482 assert(p);
5483
3a8a9163 5484 for (t = p; *t; t++) {
6294aa76 5485 if (ok && strchr(ok, *t))
1cb1767a 5486 continue;
6294aa76
LP
5487
5488 if (*t > 0 && *t < ' ')
4d1a6904
LP
5489 return true;
5490
3a8a9163
LP
5491 if (*t == 127)
5492 return true;
5493 }
5494
4d1a6904
LP
5495 return false;
5496}
5497
e884315e
LP
5498bool path_is_safe(const char *p) {
5499
5500 if (isempty(p))
5501 return false;
5502
5503 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5504 return false;
5505
5506 if (strlen(p) > PATH_MAX)
5507 return false;
5508
5509 /* The following two checks are not really dangerous, but hey, they still are confusing */
5510 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5511 return false;
5512
5513 if (strstr(p, "//"))
5514 return false;
5515
5516 return true;
5517}
5518
a9e12476
KS
5519/* hey glibc, APIs with callbacks without a user pointer are so useless */
5520void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
1c574591 5521 int (*compar) (const void *, const void *, void *), void *arg) {
a9e12476
KS
5522 size_t l, u, idx;
5523 const void *p;
5524 int comparison;
5525
5526 l = 0;
5527 u = nmemb;
5528 while (l < u) {
5529 idx = (l + u) / 2;
5530 p = (void *)(((const char *) base) + (idx * size));
5531 comparison = compar(key, p, arg);
5532 if (comparison < 0)
5533 u = idx;
5534 else if (comparison > 0)
5535 l = idx + 1;
5536 else
5537 return (void *)p;
5538 }
5539 return NULL;
5540}
09017585
MS
5541
5542bool is_locale_utf8(void) {
5543 const char *set;
5544 static int cached_answer = -1;
5545
5546 if (cached_answer >= 0)
5547 goto out;
5548
5549 if (!setlocale(LC_ALL, "")) {
5550 cached_answer = true;
5551 goto out;
5552 }
5553
5554 set = nl_langinfo(CODESET);
5555 if (!set) {
5556 cached_answer = true;
5557 goto out;
5558 }
5559
f168c273 5560 if (streq(set, "UTF-8")) {
fee79e01
HH
5561 cached_answer = true;
5562 goto out;
5563 }
5564
6cf2f1d9
HH
5565 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5566 * unset and everything can do to UTF-8 nowadays. */
fee79e01
HH
5567 set = setlocale(LC_CTYPE, NULL);
5568 if (!set) {
5569 cached_answer = true;
5570 goto out;
5571 }
5572
6cf2f1d9
HH
5573 /* Check result, but ignore the result if C was set
5574 * explicitly. */
5575 cached_answer =
5576 streq(set, "C") &&
5577 !getenv("LC_ALL") &&
5578 !getenv("LC_CTYPE") &&
5579 !getenv("LANG");
fee79e01 5580
09017585 5581out:
6cf2f1d9 5582 return (bool) cached_answer;
09017585 5583}
c339d977
MS
5584
5585const char *draw_special_char(DrawSpecialChar ch) {
5586 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
6b01f1d3 5587
c339d977 5588 /* UTF-8 */ {
6b01f1d3 5589 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
45a5ff0d
MS
5590 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5591 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
55c0b89c 5592 [DRAW_TREE_SPACE] = " ", /* */
6b01f1d3
LP
5593 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
5594 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
5595 [DRAW_ARROW] = "\342\206\222", /* → */
13f8b8cb 5596 [DRAW_DASH] = "\342\200\223", /* – */
c339d977 5597 },
6b01f1d3 5598
c339d977 5599 /* ASCII fallback */ {
6b01f1d3 5600 [DRAW_TREE_VERTICAL] = "| ",
45a5ff0d
MS
5601 [DRAW_TREE_BRANCH] = "|-",
5602 [DRAW_TREE_RIGHT] = "`-",
55c0b89c 5603 [DRAW_TREE_SPACE] = " ",
6b01f1d3
LP
5604 [DRAW_TRIANGULAR_BULLET] = ">",
5605 [DRAW_BLACK_CIRCLE] = "*",
5606 [DRAW_ARROW] = "->",
13f8b8cb 5607 [DRAW_DASH] = "-",
c339d977
MS
5608 }
5609 };
5610
5611 return draw_table[!is_locale_utf8()][ch];
5612}
409bc9c3
LP
5613
5614char *strreplace(const char *text, const char *old_string, const char *new_string) {
5615 const char *f;
5616 char *t, *r;
5617 size_t l, old_len, new_len;
5618
5619 assert(text);
5620 assert(old_string);
5621 assert(new_string);
5622
5623 old_len = strlen(old_string);
5624 new_len = strlen(new_string);
5625
5626 l = strlen(text);
5627 r = new(char, l+1);
5628 if (!r)
5629 return NULL;
5630
5631 f = text;
5632 t = r;
5633 while (*f) {
5634 char *a;
5635 size_t d, nl;
5636
5637 if (!startswith(f, old_string)) {
5638 *(t++) = *(f++);
5639 continue;
5640 }
5641
5642 d = t - r;
5643 nl = l - old_len + new_len;
5644 a = realloc(r, nl + 1);
5645 if (!a)
5646 goto oom;
5647
5648 l = nl;
5649 r = a;
5650 t = r + d;
5651
5652 t = stpcpy(t, new_string);
5653 f += old_len;
5654 }
5655
5656 *t = 0;
5657 return r;
5658
5659oom:
5660 free(r);
5661 return NULL;
5662}
e8bc0ea2
LP
5663
5664char *strip_tab_ansi(char **ibuf, size_t *_isz) {
660ddc72 5665 const char *i, *begin = NULL;
e8bc0ea2
LP
5666 enum {
5667 STATE_OTHER,
5668 STATE_ESCAPE,
5669 STATE_BRACKET
5670 } state = STATE_OTHER;
5671 char *obuf = NULL;
5672 size_t osz = 0, isz;
5673 FILE *f;
5674
5675 assert(ibuf);
5676 assert(*ibuf);
5677
5678 /* Strips ANSI color and replaces TABs by 8 spaces */
5679
5680 isz = _isz ? *_isz : strlen(*ibuf);
5681
5682 f = open_memstream(&obuf, &osz);
5683 if (!f)
5684 return NULL;
5685
5686 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5687
5688 switch (state) {
5689
5690 case STATE_OTHER:
5691 if (i >= *ibuf + isz) /* EOT */
5692 break;
5693 else if (*i == '\x1B')
5694 state = STATE_ESCAPE;
5695 else if (*i == '\t')
5696 fputs(" ", f);
5697 else
5698 fputc(*i, f);
5699 break;
5700
5701 case STATE_ESCAPE:
5702 if (i >= *ibuf + isz) { /* EOT */
5703 fputc('\x1B', f);
5704 break;
5705 } else if (*i == '[') {
5706 state = STATE_BRACKET;
5707 begin = i + 1;
5708 } else {
5709 fputc('\x1B', f);
5710 fputc(*i, f);
5711 state = STATE_OTHER;
5712 }
5713
5714 break;
5715
5716 case STATE_BRACKET:
5717
5718 if (i >= *ibuf + isz || /* EOT */
5719 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5720 fputc('\x1B', f);
5721 fputc('[', f);
5722 state = STATE_OTHER;
5723 i = begin-1;
5724 } else if (*i == 'm')
5725 state = STATE_OTHER;
5726 break;
5727 }
5728 }
5729
5730 if (ferror(f)) {
5731 fclose(f);
5732 free(obuf);
5733 return NULL;
5734 }
5735
5736 fclose(f);
5737
5738 free(*ibuf);
5739 *ibuf = obuf;
5740
5741 if (_isz)
5742 *_isz = osz;
5743
5744 return obuf;
5745}
240dbaa4
LP
5746
5747int on_ac_power(void) {
5748 bool found_offline = false, found_online = false;
5749 _cleanup_closedir_ DIR *d = NULL;
5750
5751 d = opendir("/sys/class/power_supply");
5752 if (!d)
5753 return -errno;
5754
5755 for (;;) {
5756 struct dirent *de;
240dbaa4
LP
5757 _cleanup_close_ int fd = -1, device = -1;
5758 char contents[6];
5759 ssize_t n;
240dbaa4 5760
3fd11280
FW
5761 errno = 0;
5762 de = readdir(d);
5763 if (!de && errno != 0)
5764 return -errno;
240dbaa4
LP
5765
5766 if (!de)
5767 break;
5768
5769 if (ignore_file(de->d_name))
5770 continue;
5771
5772 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5773 if (device < 0) {
5774 if (errno == ENOENT || errno == ENOTDIR)
5775 continue;
5776
5777 return -errno;
5778 }
5779
5780 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5781 if (fd < 0) {
5782 if (errno == ENOENT)
5783 continue;
5784
5785 return -errno;
5786 }
5787
5788 n = read(fd, contents, sizeof(contents));
5789 if (n < 0)
5790 return -errno;
5791
5792 if (n != 6 || memcmp(contents, "Mains\n", 6))
5793 continue;
5794
03e334a1 5795 safe_close(fd);
240dbaa4
LP
5796 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5797 if (fd < 0) {
5798 if (errno == ENOENT)
5799 continue;
5800
5801 return -errno;
5802 }
5803
5804 n = read(fd, contents, sizeof(contents));
5805 if (n < 0)
5806 return -errno;
5807
5808 if (n != 2 || contents[1] != '\n')
5809 return -EIO;
5810
5811 if (contents[0] == '1') {
5812 found_online = true;
5813 break;
5814 } else if (contents[0] == '0')
5815 found_offline = true;
5816 else
5817 return -EIO;
5818 }
5819
5820 return found_online || !found_offline;
5821}
fabe5c0e 5822
4cf7ea55 5823static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
fabe5c0e
LP
5824 char **i;
5825
5826 assert(path);
5827 assert(mode);
5828 assert(_f);
5829
7d8da2c9 5830 if (!path_strv_resolve_uniq(search, root))
fabe5c0e
LP
5831 return -ENOMEM;
5832
5833 STRV_FOREACH(i, search) {
5834 _cleanup_free_ char *p = NULL;
5835 FILE *f;
5836
375eadd9
MM
5837 if (root)
5838 p = strjoin(root, *i, "/", path, NULL);
5839 else
5840 p = strjoin(*i, "/", path, NULL);
fabe5c0e
LP
5841 if (!p)
5842 return -ENOMEM;
5843
5844 f = fopen(p, mode);
5845 if (f) {
5846 *_f = f;
5847 return 0;
5848 }
5849
5850 if (errno != ENOENT)
5851 return -errno;
5852 }
5853
5854 return -ENOENT;
5855}
5856
4cf7ea55 5857int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
fabe5c0e
LP
5858 _cleanup_strv_free_ char **copy = NULL;
5859
5860 assert(path);
5861 assert(mode);
5862 assert(_f);
5863
5864 if (path_is_absolute(path)) {
5865 FILE *f;
5866
5867 f = fopen(path, mode);
5868 if (f) {
5869 *_f = f;
5870 return 0;
5871 }
5872
5873 return -errno;
5874 }
5875
5876 copy = strv_copy((char**) search);
5877 if (!copy)
5878 return -ENOMEM;
5879
4cf7ea55 5880 return search_and_fopen_internal(path, mode, root, copy, _f);
fabe5c0e
LP
5881}
5882
4cf7ea55 5883int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
fabe5c0e
LP
5884 _cleanup_strv_free_ char **s = NULL;
5885
5886 if (path_is_absolute(path)) {
5887 FILE *f;
5888
5889 f = fopen(path, mode);
5890 if (f) {
5891 *_f = f;
5892 return 0;
5893 }
5894
5895 return -errno;
5896 }
5897
5898 s = strv_split_nulstr(search);
5899 if (!s)
5900 return -ENOMEM;
5901
4cf7ea55 5902 return search_and_fopen_internal(path, mode, root, s, _f);
fabe5c0e 5903}
c17ec25e 5904
66e35261
LP
5905char *strextend(char **x, ...) {
5906 va_list ap;
5907 size_t f, l;
5908 char *r, *p;
5909
5910 assert(x);
5911
5912 l = f = *x ? strlen(*x) : 0;
5913
5914 va_start(ap, x);
5915 for (;;) {
5916 const char *t;
5917 size_t n;
5918
5919 t = va_arg(ap, const char *);
5920 if (!t)
5921 break;
5922
5923 n = strlen(t);
5924 if (n > ((size_t) -1) - l) {
5925 va_end(ap);
5926 return NULL;
5927 }
5928
5929 l += n;
5930 }
5931 va_end(ap);
5932
5933 r = realloc(*x, l+1);
5934 if (!r)
5935 return NULL;
5936
5937 p = r + f;
5938
5939 va_start(ap, x);
5940 for (;;) {
5941 const char *t;
5942
5943 t = va_arg(ap, const char *);
5944 if (!t)
5945 break;
5946
5947 p = stpcpy(p, t);
5948 }
5949 va_end(ap);
5950
5951 *p = 0;
5952 *x = r;
5953
5954 return r + l;
5955}
9a17484d
LP
5956
5957char *strrep(const char *s, unsigned n) {
5958 size_t l;
5959 char *r, *p;
5960 unsigned i;
5961
5962 assert(s);
5963
5964 l = strlen(s);
5965 p = r = malloc(l * n + 1);
5966 if (!r)
5967 return NULL;
5968
5969 for (i = 0; i < n; i++)
5970 p = stpcpy(p, s);
5971
5972 *p = 0;
5973 return r;
5974}
392d5b37 5975
ca2d3784
ZJS
5976void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
5977 size_t a, newalloc;
392d5b37
LP
5978 void *q;
5979
98088803 5980 assert(p);
e93c33d4
SL
5981 assert(allocated);
5982
392d5b37
LP
5983 if (*allocated >= need)
5984 return *p;
5985
ca2d3784
ZJS
5986 newalloc = MAX(need * 2, 64u / size);
5987 a = newalloc * size;
98088803
LP
5988
5989 /* check for overflows */
ca2d3784 5990 if (a < size * need)
98088803
LP
5991 return NULL;
5992
392d5b37
LP
5993 q = realloc(*p, a);
5994 if (!q)
5995 return NULL;
5996
5997 *p = q;
ca2d3784 5998 *allocated = newalloc;
392d5b37
LP
5999 return q;
6000}
aa96c6cb 6001
ca2d3784 6002void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
98088803 6003 size_t prev;
4545a231
DH
6004 uint8_t *q;
6005
98088803
LP
6006 assert(p);
6007 assert(allocated);
6008
6009 prev = *allocated;
6010
ca2d3784 6011 q = greedy_realloc(p, allocated, need, size);
4545a231
DH
6012 if (!q)
6013 return NULL;
6014
6015 if (*allocated > prev)
ca2d3784 6016 memzero(q + prev * size, (*allocated - prev) * size);
4545a231
DH
6017
6018 return q;
6019}
6020
aa96c6cb
LP
6021bool id128_is_valid(const char *s) {
6022 size_t i, l;
6023
6024 l = strlen(s);
6025 if (l == 32) {
6026
6027 /* Simple formatted 128bit hex string */
6028
6029 for (i = 0; i < l; i++) {
6030 char c = s[i];
6031
6032 if (!(c >= '0' && c <= '9') &&
6033 !(c >= 'a' && c <= 'z') &&
6034 !(c >= 'A' && c <= 'Z'))
6035 return false;
6036 }
6037
6038 } else if (l == 36) {
6039
6040 /* Formatted UUID */
6041
6042 for (i = 0; i < l; i++) {
6043 char c = s[i];
6044
6045 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
6046 if (c != '-')
6047 return false;
6048 } else {
6049 if (!(c >= '0' && c <= '9') &&
6050 !(c >= 'a' && c <= 'z') &&
6051 !(c >= 'A' && c <= 'Z'))
6052 return false;
6053 }
6054 }
6055
6056 } else
6057 return false;
6058
6059 return true;
6060}
7085053a 6061
d4ac85c6
LP
6062int split_pair(const char *s, const char *sep, char **l, char **r) {
6063 char *x, *a, *b;
6064
6065 assert(s);
6066 assert(sep);
6067 assert(l);
6068 assert(r);
6069
6070 if (isempty(sep))
6071 return -EINVAL;
6072
6073 x = strstr(s, sep);
6074 if (!x)
6075 return -EINVAL;
6076
6077 a = strndup(s, x - s);
6078 if (!a)
6079 return -ENOMEM;
6080
6081 b = strdup(x + strlen(sep));
6082 if (!b) {
6083 free(a);
6084 return -ENOMEM;
6085 }
6086
6087 *l = a;
6088 *r = b;
6089
6090 return 0;
6091}
295edddf 6092
74df0fca 6093int shall_restore_state(void) {
059cb385 6094 _cleanup_free_ char *line = NULL;
a2a5291b 6095 const char *word, *state;
295edddf 6096 size_t l;
74df0fca 6097 int r;
295edddf 6098
74df0fca
LP
6099 r = proc_cmdline(&line);
6100 if (r < 0)
6101 return r;
6102 if (r == 0) /* Container ... */
6103 return 1;
295edddf 6104
059cb385 6105 r = 1;
74df0fca 6106
a2a5291b 6107 FOREACH_WORD_QUOTED(word, l, line, state) {
059cb385
LP
6108 const char *e;
6109 char n[l+1];
6110 int k;
6111
a2a5291b 6112 memcpy(n, word, l);
059cb385
LP
6113 n[l] = 0;
6114
6115 e = startswith(n, "systemd.restore_state=");
6116 if (!e)
6117 continue;
6118
6119 k = parse_boolean(e);
6120 if (k >= 0)
6121 r = k;
6122 }
6123
6124 return r;
74df0fca
LP
6125}
6126
6127int proc_cmdline(char **ret) {
6128 int r;
6129
6130 if (detect_container(NULL) > 0) {
39883f62 6131 char *buf = NULL, *p;
02bb6cda
LP
6132 size_t sz = 0;
6133
6134 r = read_full_file("/proc/1/cmdline", &buf, &sz);
6135 if (r < 0)
6136 return r;
6137
6138 for (p = buf; p + 1 < buf + sz; p++)
6139 if (*p == 0)
6140 *p = ' ';
6141
059cb385 6142 *p = 0;
02bb6cda
LP
6143 *ret = buf;
6144 return 1;
295edddf
TG
6145 }
6146
74df0fca
LP
6147 r = read_one_line_file("/proc/cmdline", ret);
6148 if (r < 0)
6149 return r;
295edddf 6150
74df0fca 6151 return 1;
295edddf 6152}
bc9fd78c 6153
059cb385 6154int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
141a79f4 6155 _cleanup_free_ char *line = NULL;
a2a5291b 6156 const char *w, *state;
141a79f4
ZJS
6157 size_t l;
6158 int r;
6159
059cb385
LP
6160 assert(parse_item);
6161
141a79f4
ZJS
6162 r = proc_cmdline(&line);
6163 if (r < 0)
6164 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
6165 if (r <= 0)
6166 return 0;
6167
6168 FOREACH_WORD_QUOTED(w, l, line, state) {
059cb385 6169 char word[l+1], *value;
141a79f4 6170
059cb385
LP
6171 memcpy(word, w, l);
6172 word[l] = 0;
141a79f4 6173
059cb385
LP
6174 /* Filter out arguments that are intended only for the
6175 * initrd */
6176 if (!in_initrd() && startswith(word, "rd."))
6177 continue;
6178
6179 value = strchr(word, '=');
6180 if (value)
6181 *(value++) = 0;
6182
6183 r = parse_item(word, value);
6184 if (r < 0)
141a79f4 6185 return r;
141a79f4
ZJS
6186 }
6187
6188 return 0;
6189}
6190
bc9fd78c
LP
6191int container_get_leader(const char *machine, pid_t *pid) {
6192 _cleanup_free_ char *s = NULL, *class = NULL;
6193 const char *p;
6194 pid_t leader;
6195 int r;
6196
6197 assert(machine);
6198 assert(pid);
6199
6200 p = strappenda("/run/systemd/machines/", machine);
6201 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
6202 if (r == -ENOENT)
6203 return -EHOSTDOWN;
6204 if (r < 0)
6205 return r;
6206 if (!s)
6207 return -EIO;
6208
6209 if (!streq_ptr(class, "container"))
6210 return -EIO;
6211
6212 r = parse_pid(s, &leader);
6213 if (r < 0)
6214 return r;
6215 if (leader <= 1)
6216 return -EIO;
6217
6218 *pid = leader;
6219 return 0;
6220}
6221
878cd7e9
LP
6222int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
6223 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
359a06aa 6224 int rfd = -1;
bc9fd78c
LP
6225
6226 assert(pid >= 0);
bc9fd78c 6227
878cd7e9
LP
6228 if (mntns_fd) {
6229 const char *mntns;
a4475f57 6230
878cd7e9
LP
6231 mntns = procfs_file_alloca(pid, "ns/mnt");
6232 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6233 if (mntnsfd < 0)
6234 return -errno;
6235 }
bc9fd78c 6236
878cd7e9
LP
6237 if (pidns_fd) {
6238 const char *pidns;
6239
6240 pidns = procfs_file_alloca(pid, "ns/pid");
6241 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6242 if (pidnsfd < 0)
6243 return -errno;
6244 }
6245
6246 if (netns_fd) {
6247 const char *netns;
6248
6249 netns = procfs_file_alloca(pid, "ns/net");
6250 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6251 if (netnsfd < 0)
6252 return -errno;
6253 }
6254
6255 if (root_fd) {
6256 const char *root;
6257
6258 root = procfs_file_alloca(pid, "root");
6259 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
6260 if (rfd < 0)
6261 return -errno;
6262 }
6263
6264 if (pidns_fd)
6265 *pidns_fd = pidnsfd;
bc9fd78c 6266
878cd7e9
LP
6267 if (mntns_fd)
6268 *mntns_fd = mntnsfd;
6269
6270 if (netns_fd)
6271 *netns_fd = netnsfd;
6272
6273 if (root_fd)
6274 *root_fd = rfd;
6275
6276 pidnsfd = mntnsfd = netnsfd = -1;
bc9fd78c
LP
6277
6278 return 0;
6279}
6280
878cd7e9 6281int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
bc9fd78c 6282
878cd7e9
LP
6283 if (pidns_fd >= 0)
6284 if (setns(pidns_fd, CLONE_NEWPID) < 0)
6285 return -errno;
a4475f57 6286
878cd7e9
LP
6287 if (mntns_fd >= 0)
6288 if (setns(mntns_fd, CLONE_NEWNS) < 0)
6289 return -errno;
bc9fd78c 6290
878cd7e9
LP
6291 if (netns_fd >= 0)
6292 if (setns(netns_fd, CLONE_NEWNET) < 0)
6293 return -errno;
bc9fd78c 6294
878cd7e9
LP
6295 if (root_fd >= 0) {
6296 if (fchdir(root_fd) < 0)
6297 return -errno;
6298
6299 if (chroot(".") < 0)
6300 return -errno;
6301 }
bc9fd78c 6302
5e2b3214
LP
6303 if (setresgid(0, 0, 0) < 0)
6304 return -errno;
6305
878cd7e9
LP
6306 if (setgroups(0, NULL) < 0)
6307 return -errno;
6308
5e2b3214
LP
6309 if (setresuid(0, 0, 0) < 0)
6310 return -errno;
6311
bc9fd78c
LP
6312 return 0;
6313}
bf108e55 6314
9f5650ae
LP
6315bool pid_is_unwaited(pid_t pid) {
6316 /* Checks whether a PID is still valid at all, including a zombie */
6317
bf108e55
LP
6318 if (pid <= 0)
6319 return false;
6320
6321 if (kill(pid, 0) >= 0)
6322 return true;
6323
6324 return errno != ESRCH;
6325}
eff05270 6326
9f5650ae
LP
6327bool pid_is_alive(pid_t pid) {
6328 int r;
6329
6330 /* Checks whether a PID is still valid and not a zombie */
6331
6332 if (pid <= 0)
6333 return false;
6334
6335 r = get_process_state(pid);
6336 if (r == -ENOENT || r == 'Z')
6337 return false;
6338
6339 return true;
6340}
6341
eff05270
LP
6342int getpeercred(int fd, struct ucred *ucred) {
6343 socklen_t n = sizeof(struct ucred);
6344 struct ucred u;
6345 int r;
6346
6347 assert(fd >= 0);
6348 assert(ucred);
6349
6350 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6351 if (r < 0)
6352 return -errno;
6353
6354 if (n != sizeof(struct ucred))
6355 return -EIO;
6356
6357 /* Check if the data is actually useful and not suppressed due
6358 * to namespacing issues */
6359 if (u.pid <= 0)
6360 return -ENODATA;
6361
6362 *ucred = u;
6363 return 0;
6364}
6365
6366int getpeersec(int fd, char **ret) {
6367 socklen_t n = 64;
6368 char *s;
6369 int r;
6370
6371 assert(fd >= 0);
6372 assert(ret);
6373
6374 s = new0(char, n);
6375 if (!s)
6376 return -ENOMEM;
6377
6378 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6379 if (r < 0) {
6380 free(s);
6381
6382 if (errno != ERANGE)
6383 return -errno;
6384
6385 s = new0(char, n);
6386 if (!s)
6387 return -ENOMEM;
6388
6389 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6390 if (r < 0) {
6391 free(s);
6392 return -errno;
6393 }
6394 }
6395
ae98841e
LP
6396 if (isempty(s)) {
6397 free(s);
6398 return -ENOTSUP;
6399 }
6400
eff05270
LP
6401 *ret = s;
6402 return 0;
6403}
8e33886e 6404
0f010ef2 6405/* This is much like like mkostemp() but is subject to umask(). */
65b3903f 6406int mkostemp_safe(char *pattern, int flags) {
2d5bdf5b 6407 _cleanup_umask_ mode_t u;
0f010ef2 6408 int fd;
65b3903f 6409
d37a91e8 6410 assert(pattern);
65b3903f 6411
2d5bdf5b
LP
6412 u = umask(077);
6413
0f010ef2
ZJS
6414 fd = mkostemp(pattern, flags);
6415 if (fd < 0)
6416 return -errno;
65b3903f 6417
0f010ef2 6418 return fd;
65b3903f
ZJS
6419}
6420
8e33886e 6421int open_tmpfile(const char *path, int flags) {
8e33886e 6422 char *p;
a6afc4ae
LP
6423 int fd;
6424
6425 assert(path);
8e33886e
ZJS
6426
6427#ifdef O_TMPFILE
7736202c
LP
6428 /* Try O_TMPFILE first, if it is supported */
6429 fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
8e33886e
ZJS
6430 if (fd >= 0)
6431 return fd;
6432#endif
7736202c
LP
6433
6434 /* Fall back to unguessable name + unlinking */
8e33886e
ZJS
6435 p = strappenda(path, "/systemd-tmp-XXXXXX");
6436
a6afc4ae 6437 fd = mkostemp_safe(p, flags);
8e33886e 6438 if (fd < 0)
65b3903f 6439 return fd;
8e33886e
ZJS
6440
6441 unlink(p);
6442 return fd;
6443}
fdb9161c
LP
6444
6445int fd_warn_permissions(const char *path, int fd) {
6446 struct stat st;
6447
6448 if (fstat(fd, &st) < 0)
6449 return -errno;
6450
6451 if (st.st_mode & 0111)
6452 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6453
6454 if (st.st_mode & 0002)
6455 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6456
6457 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6458 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);
6459
6460 return 0;
6461}
6afc95b7 6462
ac45f971 6463unsigned long personality_from_string(const char *p) {
6afc95b7
LP
6464
6465 /* Parse a personality specifier. We introduce our own
6466 * identifiers that indicate specific ABIs, rather than just
6467 * hints regarding the register size, since we want to keep
6468 * things open for multiple locally supported ABIs for the
6469 * same register size. We try to reuse the ABI identifiers
6470 * used by libseccomp. */
6471
6472#if defined(__x86_64__)
6473
6474 if (streq(p, "x86"))
6475 return PER_LINUX32;
6476
6477 if (streq(p, "x86-64"))
6478 return PER_LINUX;
6479
6480#elif defined(__i386__)
6481
6482 if (streq(p, "x86"))
6483 return PER_LINUX;
6484#endif
6485
6486 /* personality(7) documents that 0xffffffffUL is used for
6487 * querying the current personality, hence let's use that here
6488 * as error indicator. */
6489 return 0xffffffffUL;
6490}
ac45f971
LP
6491
6492const char* personality_to_string(unsigned long p) {
6493
6494#if defined(__x86_64__)
6495
6496 if (p == PER_LINUX32)
6497 return "x86";
6498
6499 if (p == PER_LINUX)
6500 return "x86-64";
6501
6502#elif defined(__i386__)
6503
6504 if (p == PER_LINUX)
6505 return "x86";
6506#endif
6507
6508 return NULL;
6509}
1c231f56
LP
6510
6511uint64_t physical_memory(void) {
6512 long mem;
6513
6514 /* We return this as uint64_t in case we are running as 32bit
6515 * process on a 64bit kernel with huge amounts of memory */
6516
6517 mem = sysconf(_SC_PHYS_PAGES);
6518 assert(mem > 0);
6519
6520 return (uint64_t) mem * (uint64_t) page_size();
6521}
6db615c1
LP
6522
6523char* mount_test_option(const char *haystack, const char *needle) {
6524
6525 struct mntent me = {
6526 .mnt_opts = (char*) haystack
6527 };
6528
6529 assert(needle);
6530
6531 /* Like glibc's hasmntopt(), but works on a string, not a
6532 * struct mntent */
6533
6534 if (!haystack)
6535 return NULL;
6536
6537 return hasmntopt(&me, needle);
6538}
29bfbcd6
LP
6539
6540void hexdump(FILE *f, const void *p, size_t s) {
6541 const uint8_t *b = p;
6542 unsigned n = 0;
6543
6544 assert(s == 0 || b);
6545
6546 while (s > 0) {
6547 size_t i;
6548
6549 fprintf(f, "%04x ", n);
6550
6551 for (i = 0; i < 16; i++) {
6552
6553 if (i >= s)
6554 fputs(" ", f);
6555 else
6556 fprintf(f, "%02x ", b[i]);
6557
6558 if (i == 7)
6559 fputc(' ', f);
6560 }
6561
6562 fputc(' ', f);
6563
6564 for (i = 0; i < 16; i++) {
6565
6566 if (i >= s)
6567 fputc(' ', f);
6568 else
6569 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
6570 }
6571
6572 fputc('\n', f);
6573
6574 if (s < 16)
6575 break;
6576
6577 n += 16;
6578 b += 16;
6579 s -= 16;
6580 }
6581}
c5220a94 6582
966bff26 6583int update_reboot_param_file(const char *param) {
c5220a94
MO
6584 int r = 0;
6585
6586 if (param) {
6587
6588 r = write_string_file(REBOOT_PARAM_FILE, param);
6589 if (r < 0)
6590 log_error("Failed to write reboot param to "
6591 REBOOT_PARAM_FILE": %s", strerror(-r));
6592 } else
6593 unlink(REBOOT_PARAM_FILE);
6594
6595 return r;
6596}
6d313367
LP
6597
6598int umount_recursive(const char *prefix, int flags) {
6599 bool again;
6600 int n = 0, r;
6601
6602 /* Try to umount everything recursively below a
6603 * directory. Also, take care of stacked mounts, and keep
6604 * unmounting them until they are gone. */
6605
6606 do {
6607 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6608
6609 again = false;
6610 r = 0;
6611
6612 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6613 if (!proc_self_mountinfo)
6614 return -errno;
6615
6616 for (;;) {
6617 _cleanup_free_ char *path = NULL, *p = NULL;
6618 int k;
6619
6620 k = fscanf(proc_self_mountinfo,
6621 "%*s " /* (1) mount id */
6622 "%*s " /* (2) parent id */
6623 "%*s " /* (3) major:minor */
6624 "%*s " /* (4) root */
6625 "%ms " /* (5) mount point */
6626 "%*s" /* (6) mount options */
6627 "%*[^-]" /* (7) optional fields */
6628 "- " /* (8) separator */
6629 "%*s " /* (9) file system type */
6630 "%*s" /* (10) mount source */
6631 "%*s" /* (11) mount options 2 */
6632 "%*[^\n]", /* some rubbish at the end */
6633 &path);
6d313367
LP
6634 if (k != 1) {
6635 if (k == EOF)
6636 break;
6637
6638 continue;
6639 }
6640
6641 p = cunescape(path);
6642 if (!p)
6643 return -ENOMEM;
6644
6645 if (!path_startswith(p, prefix))
6646 continue;
6647
6648 if (umount2(p, flags) < 0) {
6649 r = -errno;
6650 continue;
6651 }
6652
6653 again = true;
6654 n++;
6655
6656 break;
6657 }
6658
6659 } while (again);
6660
6661 return r ? r : n;
6662}
d6797c92
LP
6663
6664int bind_remount_recursive(const char *prefix, bool ro) {
6665 _cleanup_set_free_free_ Set *done = NULL;
6666 _cleanup_free_ char *cleaned = NULL;
6667 int r;
6668
6669 /* Recursively remount a directory (and all its submounts)
6670 * read-only or read-write. If the directory is already
6671 * mounted, we reuse the mount and simply mark it
6672 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6673 * operation). If it isn't we first make it one. Afterwards we
6674 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6675 * submounts we can access, too. When mounts are stacked on
6676 * the same mount point we only care for each individual
6677 * "top-level" mount on each point, as we cannot
6678 * influence/access the underlying mounts anyway. We do not
6679 * have any effect on future submounts that might get
6680 * propagated, they migt be writable. This includes future
6681 * submounts that have been triggered via autofs. */
6682
6683 cleaned = strdup(prefix);
6684 if (!cleaned)
6685 return -ENOMEM;
6686
6687 path_kill_slashes(cleaned);
6688
6689 done = set_new(string_hash_func, string_compare_func);
6690 if (!done)
6691 return -ENOMEM;
6692
6693 for (;;) {
6694 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6695 _cleanup_set_free_free_ Set *todo = NULL;
6696 bool top_autofs = false;
6697 char *x;
6698
6699 todo = set_new(string_hash_func, string_compare_func);
6700 if (!todo)
6701 return -ENOMEM;
6702
6703 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6704 if (!proc_self_mountinfo)
6705 return -errno;
6706
6707 for (;;) {
6708 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
6709 int k;
6710
6711 k = fscanf(proc_self_mountinfo,
6712 "%*s " /* (1) mount id */
6713 "%*s " /* (2) parent id */
6714 "%*s " /* (3) major:minor */
6715 "%*s " /* (4) root */
6716 "%ms " /* (5) mount point */
6717 "%*s" /* (6) mount options (superblock) */
6718 "%*[^-]" /* (7) optional fields */
6719 "- " /* (8) separator */
6720 "%ms " /* (9) file system type */
6721 "%*s" /* (10) mount source */
6722 "%*s" /* (11) mount options (bind mount) */
6723 "%*[^\n]", /* some rubbish at the end */
6724 &path,
6725 &type);
6726 if (k != 2) {
6727 if (k == EOF)
6728 break;
6729
6730 continue;
6731 }
6732
6733 p = cunescape(path);
6734 if (!p)
6735 return -ENOMEM;
6736
6737 /* Let's ignore autofs mounts. If they aren't
6738 * triggered yet, we want to avoid triggering
6739 * them, as we don't make any guarantees for
6740 * future submounts anyway. If they are
6741 * already triggered, then we will find
6742 * another entry for this. */
6743 if (streq(type, "autofs")) {
6744 top_autofs = top_autofs || path_equal(cleaned, p);
6745 continue;
6746 }
6747
6748 if (path_startswith(p, cleaned) &&
6749 !set_contains(done, p)) {
6750
6751 r = set_consume(todo, p);
6752 p = NULL;
6753
6754 if (r == -EEXIST)
6755 continue;
6756 if (r < 0)
6757 return r;
6758 }
6759 }
6760
6761 /* If we have no submounts to process anymore and if
6762 * the root is either already done, or an autofs, we
6763 * are done */
6764 if (set_isempty(todo) &&
6765 (top_autofs || set_contains(done, cleaned)))
6766 return 0;
6767
6768 if (!set_contains(done, cleaned) &&
6769 !set_contains(todo, cleaned)) {
6770 /* The prefix directory itself is not yet a
6771 * mount, make it one. */
6772 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
6773 return -errno;
6774
6775 if (mount(NULL, prefix, NULL, MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
6776 return -errno;
6777
6778 x = strdup(cleaned);
6779 if (!x)
6780 return -ENOMEM;
6781
6782 r = set_consume(done, x);
6783 if (r < 0)
6784 return r;
6785 }
6786
6787 while ((x = set_steal_first(todo))) {
6788
6789 r = set_consume(done, x);
6790 if (r == -EEXIST)
6791 continue;
6792 if (r < 0)
6793 return r;
6794
6795 if (mount(NULL, x, NULL, MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
6796
6797 /* Deal with mount points that are
6798 * obstructed by a later mount */
6799
6800 if (errno != ENOENT)
6801 return -errno;
6802 }
6803
6804 }
6805 }
6806}
1b992147
LP
6807
6808int fflush_and_check(FILE *f) {
45c196a7 6809 assert(f);
1b992147
LP
6810
6811 errno = 0;
6812 fflush(f);
6813
6814 if (ferror(f))
6815 return errno ? -errno : -EIO;
6816
6817 return 0;
6818}
2e78fa79
LP
6819
6820char *tempfn_xxxxxx(const char *p) {
6821 const char *fn;
6822 char *t;
6823 size_t k;
6824
6825 assert(p);
6826
6827 t = new(char, strlen(p) + 1 + 6 + 1);
6828 if (!t)
6829 return NULL;
6830
6831 fn = basename(p);
6832 k = fn - p;
6833
6834 strcpy(stpcpy(stpcpy(mempcpy(t, p, k), "."), fn), "XXXXXX");
6835
6836 return t;
6837}
6838
6839char *tempfn_random(const char *p) {
6840 const char *fn;
6841 char *t, *x;
6842 uint64_t u;
6843 size_t k;
6844 unsigned i;
6845
6846 assert(p);
6847
6848 t = new(char, strlen(p) + 1 + 16 + 1);
6849 if (!t)
6850 return NULL;
6851
6852 fn = basename(p);
6853 k = fn - p;
6854
6855 x = stpcpy(stpcpy(mempcpy(t, p, k), "."), fn);
6856
6857 u = random_u64();
6858 for (i = 0; i < 16; i++) {
6859 *(x++) = hexchar(u & 0xF);
6860 u >>= 4;
6861 }
6862
6863 *x = 0;
6864
6865 return t;
6866}
fecc80c1
LP
6867
6868/* make sure the hostname is not "localhost" */
6869bool is_localhost(const char *hostname) {
6870 assert(hostname);
6871
a0627f82
LP
6872 /* This tries to identify local host and domain names
6873 * described in RFC6761 plus the redhatism of .localdomain */
fecc80c1
LP
6874
6875 return streq(hostname, "localhost") ||
6876 streq(hostname, "localhost.") ||
a0627f82
LP
6877 streq(hostname, "localdomain.") ||
6878 streq(hostname, "localdomain") ||
fecc80c1
LP
6879 endswith(hostname, ".localhost") ||
6880 endswith(hostname, ".localhost.") ||
6881 endswith(hostname, ".localdomain") ||
6882 endswith(hostname, ".localdomain.");
6883}
45035609
LP
6884
6885int take_password_lock(const char *root) {
6886
6887 struct flock flock = {
6888 .l_type = F_WRLCK,
6889 .l_whence = SEEK_SET,
6890 .l_start = 0,
6891 .l_len = 0,
6892 };
6893
6894 const char *path;
6895 int fd, r;
6896
6897 /* This is roughly the same as lckpwdf(), but not as awful. We
6898 * don't want to use alarm() and signals, hence we implement
6899 * our own trivial version of this.
6900 *
6901 * Note that shadow-utils also takes per-database locks in
6902 * addition to lckpwdf(). However, we don't given that they
6903 * are redundant as they they invoke lckpwdf() first and keep
6904 * it during everything they do. The per-database locks are
6905 * awfully racy, and thus we just won't do them. */
6906
6907 if (root)
6908 path = strappenda(root, "/etc/.pwd.lock");
6909 else
6910 path = "/etc/.pwd.lock";
6911
6912 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
6913 if (fd < 0)
6914 return -errno;
6915
6916 r = fcntl(fd, F_SETLKW, &flock);
6917 if (r < 0) {
6918 safe_close(fd);
6919 return -errno;
6920 }
6921
6922 return fd;
6923}
5261ba90
TT
6924
6925int is_symlink(const char *path) {
6926 struct stat info;
6927
6928 if (lstat(path, &info) < 0)
6929 return -errno;
6930
6931 if (S_ISLNK(info.st_mode))
6932 return 1;
6933
6934 return 0;
a0627f82 6935}
7629889c
LP
6936
6937int unquote_first_word(const char **p, char **ret) {
6938 _cleanup_free_ char *s = NULL;
6939 size_t allocated = 0, sz = 0;
6940
6941 enum {
6942 START,
6943 VALUE,
6944 VALUE_ESCAPE,
6945 SINGLE_QUOTE,
6946 SINGLE_QUOTE_ESCAPE,
6947 DOUBLE_QUOTE,
6948 DOUBLE_QUOTE_ESCAPE,
6949 SPACE,
6950 } state = START;
6951
6952 assert(p);
6953 assert(*p);
6954 assert(ret);
6955
6956 /* Parses the first word of a string, and returns it in
6957 * *ret. Removes all quotes in the process. When parsing fails
6958 * (because of an uneven number of quotes or similar), leaves
6959 * the pointer *p at the first invalid character. */
6960
6961 for (;;) {
6962 char c = **p;
6963
6964 switch (state) {
6965
6966 case START:
6967 if (c == 0)
6968 goto finish;
6969 else if (strchr(WHITESPACE, c))
6970 break;
6971
6972 state = VALUE;
6973 /* fallthrough */
6974
6975 case VALUE:
6976 if (c == 0)
6977 goto finish;
6978 else if (c == '\'')
6979 state = SINGLE_QUOTE;
6980 else if (c == '\\')
6981 state = VALUE_ESCAPE;
6982 else if (c == '\"')
6983 state = DOUBLE_QUOTE;
6984 else if (strchr(WHITESPACE, c))
6985 state = SPACE;
6986 else {
6987 if (!GREEDY_REALLOC(s, allocated, sz+2))
6988 return -ENOMEM;
6989
6990 s[sz++] = c;
6991 }
6992
6993 break;
6994
6995 case VALUE_ESCAPE:
6996 if (c == 0)
6997 return -EINVAL;
6998
6999 if (!GREEDY_REALLOC(s, allocated, sz+2))
7000 return -ENOMEM;
7001
7002 s[sz++] = c;
7003 state = VALUE;
7004
7005 break;
7006
7007 case SINGLE_QUOTE:
7008 if (c == 0)
7009 return -EINVAL;
7010 else if (c == '\'')
7011 state = VALUE;
7012 else if (c == '\\')
7013 state = SINGLE_QUOTE_ESCAPE;
7014 else {
7015 if (!GREEDY_REALLOC(s, allocated, sz+2))
7016 return -ENOMEM;
7017
7018 s[sz++] = c;
7019 }
7020
7021 break;
7022
7023 case SINGLE_QUOTE_ESCAPE:
7024 if (c == 0)
7025 return -EINVAL;
7026
7027 if (!GREEDY_REALLOC(s, allocated, sz+2))
7028 return -ENOMEM;
7029
7030 s[sz++] = c;
7031 state = SINGLE_QUOTE;
7032 break;
7033
7034 case DOUBLE_QUOTE:
7035 if (c == 0)
7036 return -EINVAL;
7037 else if (c == '\"')
7038 state = VALUE;
7039 else if (c == '\\')
7040 state = DOUBLE_QUOTE_ESCAPE;
7041 else {
7042 if (!GREEDY_REALLOC(s, allocated, sz+2))
7043 return -ENOMEM;
7044
7045 s[sz++] = c;
7046 }
7047
7048 break;
7049
7050 case DOUBLE_QUOTE_ESCAPE:
7051 if (c == 0)
7052 return -EINVAL;
7053
7054 if (!GREEDY_REALLOC(s, allocated, sz+2))
7055 return -ENOMEM;
7056
7057 s[sz++] = c;
7058 state = DOUBLE_QUOTE;
7059 break;
7060
7061 case SPACE:
7062 if (c == 0)
7063 goto finish;
7064 if (!strchr(WHITESPACE, c))
7065 goto finish;
7066
7067 break;
7068 }
7069
7070 (*p) ++;
7071 }
7072
7073finish:
7074 if (!s) {
7075 *ret = NULL;
7076 return 0;
7077 }
7078
7079 s[sz] = 0;
7080 *ret = s;
7081 s = NULL;
7082
7083 return 1;
7084}
7085
7086int unquote_many_words(const char **p, ...) {
7087 va_list ap;
7088 char **l;
7089 int n = 0, i, c, r;
7090
7091 /* Parses a number of words from a string, stripping any
7092 * quotes if necessary. */
7093
7094 assert(p);
7095
7096 /* Count how many words are expected */
7097 va_start(ap, p);
7098 for (;;) {
7099 if (!va_arg(ap, char **))
7100 break;
7101 n++;
7102 }
7103 va_end(ap);
7104
7105 if (n <= 0)
7106 return 0;
7107
7108 /* Read all words into a temporary array */
7109 l = newa0(char*, n);
7110 for (c = 0; c < n; c++) {
7111
7112 r = unquote_first_word(p, &l[c]);
7113 if (r < 0) {
7114 int j;
7115
7116 for (j = 0; j < c; j++) {
7117 free(l[j]);
7118 return r;
7119 }
7120 }
7121
7122 if (r == 0)
7123 break;
7124 }
7125
7126 /* If we managed to parse all words, return them in the passed
7127 * in parameters */
7128 va_start(ap, p);
7129 for (i = 0; i < n; i++) {
7130 char **v;
7131
7132 v = va_arg(ap, char **);
7133 assert(v);
7134
7135 *v = l[i];
7136 }
7137 va_end(ap);
7138
7139 return c;
7140}