]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/util.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
61 #include "exit-status.h"
63 bool streq_ptr(const char *a
, const char *b
) {
65 /* Like streq(), but tries to make sense of NULL pointers */
76 usec_t
now(clockid_t clock_id
) {
79 assert_se(clock_gettime(clock_id
, &ts
) == 0);
81 return timespec_load(&ts
);
84 dual_timestamp
* dual_timestamp_get(dual_timestamp
*ts
) {
87 ts
->realtime
= now(CLOCK_REALTIME
);
88 ts
->monotonic
= now(CLOCK_MONOTONIC
);
93 usec_t
timespec_load(const struct timespec
*ts
) {
97 (usec_t
) ts
->tv_sec
* USEC_PER_SEC
+
98 (usec_t
) ts
->tv_nsec
/ NSEC_PER_USEC
;
101 struct timespec
*timespec_store(struct timespec
*ts
, usec_t u
) {
104 ts
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
105 ts
->tv_nsec
= (long int) ((u
% USEC_PER_SEC
) * NSEC_PER_USEC
);
110 usec_t
timeval_load(const struct timeval
*tv
) {
114 (usec_t
) tv
->tv_sec
* USEC_PER_SEC
+
115 (usec_t
) tv
->tv_usec
;
118 struct timeval
*timeval_store(struct timeval
*tv
, usec_t u
) {
121 tv
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
122 tv
->tv_usec
= (suseconds_t
) (u
% USEC_PER_SEC
);
127 bool endswith(const char *s
, const char *postfix
) {
134 pl
= strlen(postfix
);
142 return memcmp(s
+ sl
- pl
, postfix
, pl
) == 0;
145 bool startswith(const char *s
, const char *prefix
) {
160 return memcmp(s
, prefix
, pl
) == 0;
163 bool startswith_no_case(const char *s
, const char *prefix
) {
179 for(i
= 0; i
< pl
; ++i
) {
180 if (tolower(s
[i
]) != tolower(prefix
[i
]))
187 bool first_word(const char *s
, const char *word
) {
202 if (memcmp(s
, word
, wl
) != 0)
206 strchr(WHITESPACE
, s
[wl
]);
209 int close_nointr(int fd
) {
215 if ((r
= close(fd
)) >= 0)
223 void close_nointr_nofail(int fd
) {
224 int saved_errno
= errno
;
226 /* like close_nointr() but cannot fail, and guarantees errno
229 assert_se(close_nointr(fd
) == 0);
234 void close_many(const int fds
[], unsigned n_fd
) {
237 for (i
= 0; i
< n_fd
; i
++)
238 close_nointr_nofail(fds
[i
]);
241 int parse_boolean(const char *v
) {
244 if (streq(v
, "1") || v
[0] == 'y' || v
[0] == 'Y' || v
[0] == 't' || v
[0] == 'T' || !strcasecmp(v
, "on"))
246 else if (streq(v
, "0") || v
[0] == 'n' || v
[0] == 'N' || v
[0] == 'f' || v
[0] == 'F' || !strcasecmp(v
, "off"))
252 int parse_pid(const char *s
, pid_t
* ret_pid
) {
260 if ((r
= safe_atolu(s
, &ul
)) < 0)
265 if ((unsigned long) pid
!= ul
)
275 int safe_atou(const char *s
, unsigned *ret_u
) {
283 l
= strtoul(s
, &x
, 0);
285 if (!x
|| *x
|| errno
)
286 return errno
? -errno
: -EINVAL
;
288 if ((unsigned long) (unsigned) l
!= l
)
291 *ret_u
= (unsigned) l
;
295 int safe_atoi(const char *s
, int *ret_i
) {
303 l
= strtol(s
, &x
, 0);
305 if (!x
|| *x
|| errno
)
306 return errno
? -errno
: -EINVAL
;
308 if ((long) (int) l
!= l
)
315 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
317 unsigned long long l
;
323 l
= strtoull(s
, &x
, 0);
325 if (!x
|| *x
|| errno
)
326 return errno
? -errno
: -EINVAL
;
332 int safe_atolli(const char *s
, long long int *ret_lli
) {
340 l
= strtoll(s
, &x
, 0);
342 if (!x
|| *x
|| errno
)
343 return errno
? -errno
: -EINVAL
;
349 /* Split a string into words. */
350 char *split(const char *c
, size_t *l
, const char *separator
, char **state
) {
353 current
= *state
? *state
: (char*) c
;
355 if (!*current
|| *c
== 0)
358 current
+= strspn(current
, separator
);
359 *l
= strcspn(current
, separator
);
362 return (char*) current
;
365 /* Split a string into words, but consider strings enclosed in '' and
366 * "" as words even if they include spaces. */
367 char *split_quoted(const char *c
, size_t *l
, char **state
) {
369 bool escaped
= false;
371 current
= *state
? *state
: (char*) c
;
373 if (!*current
|| *c
== 0)
376 current
+= strspn(current
, WHITESPACE
);
378 if (*current
== '\'') {
381 for (e
= current
; *e
; e
++) {
391 *state
= *e
== 0 ? e
: e
+1;
392 } else if (*current
== '\"') {
395 for (e
= current
; *e
; e
++) {
405 *state
= *e
== 0 ? e
: e
+1;
407 for (e
= current
; *e
; e
++) {
412 else if (strchr(WHITESPACE
, *e
))
419 return (char*) current
;
422 char **split_path_and_make_absolute(const char *p
) {
426 if (!(l
= strv_split(p
, ":")))
429 if (!strv_path_make_absolute_cwd(l
)) {
437 int get_parent_of_pid(pid_t pid
, pid_t
*_ppid
) {
440 char fn
[132], line
[256], *p
;
446 assert_se(snprintf(fn
, sizeof(fn
)-1, "/proc/%lu/stat", (unsigned long) pid
) < (int) (sizeof(fn
)-1));
447 fn
[sizeof(fn
)-1] = 0;
449 if (!(f
= fopen(fn
, "r")))
452 if (!(fgets(line
, sizeof(line
), f
))) {
460 /* Let's skip the pid and comm fields. The latter is enclosed
461 * in () but does not escape any () in its value, so let's
462 * skip over it manually */
464 if (!(p
= strrchr(line
, ')')))
475 if ((long unsigned) (pid_t
) ppid
!= ppid
)
478 *_ppid
= (pid_t
) ppid
;
483 int write_one_line_file(const char *fn
, const char *line
) {
490 if (!(f
= fopen(fn
, "we")))
493 if (fputs(line
, f
) < 0) {
498 if (!endswith(line
, "\n"))
507 int read_one_line_file(const char *fn
, char **line
) {
510 char t
[LINE_MAX
], *c
;
515 if (!(f
= fopen(fn
, "re")))
518 if (!(fgets(t
, sizeof(t
), f
))) {
523 if (!(c
= strdup(t
))) {
536 int read_full_file(const char *fn
, char **contents
) {
543 if (!(f
= fopen(fn
, "re")))
546 if (fstat(fileno(f
), &st
) < 0) {
551 n
= st
.st_size
> 0 ? st
.st_size
: LINE_MAX
;
558 if (!(t
= realloc(buf
, n
+1))) {
564 k
= fread(buf
+ l
, 1, n
- l
, f
);
579 if (n
> 4*1024*1024) {
587 else if (!(buf
= calloc(1, 1))) {
606 const char *separator
, ...) {
614 if ((r
= read_full_file(fname
, &contents
)) < 0)
619 const char *key
= NULL
;
621 p
+= strspn(p
, separator
);
622 p
+= strspn(p
, WHITESPACE
);
627 if (!strchr(COMMENTS
, *p
)) {
631 va_start(ap
, separator
);
632 while ((key
= va_arg(ap
, char *))) {
636 value
= va_arg(ap
, char **);
639 if (strncmp(p
, key
, n
) != 0 ||
644 n
= strcspn(p
, separator
);
647 strchr(QUOTES
, p
[0]) &&
649 v
= strndup(p
+1, n
-2);
660 /* return empty value strings as NULL */
677 p
+= strcspn(p
, separator
);
685 char *truncate_nl(char *s
) {
688 s
[strcspn(s
, NEWLINE
)] = 0;
692 int get_process_name(pid_t pid
, char **name
) {
699 if (asprintf(&p
, "/proc/%lu/comm", (unsigned long) pid
) < 0)
702 r
= read_one_line_file(p
, name
);
712 int get_process_cmdline(pid_t pid
, size_t max_length
, char **line
) {
720 assert(max_length
> 0);
723 if (asprintf(&p
, "/proc/%lu/cmdline", (unsigned long) pid
) < 0)
732 if (!(r
= new(char, max_length
))) {
739 while ((c
= getc(f
)) != EOF
) {
761 size_t n
= MIN(left
-1, 3U);
769 /* Kernel threads have no argv[] */
776 if ((h
= get_process_name(pid
, &t
)) < 0)
779 h
= asprintf(&r
, "[%s]", t
);
790 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
798 return strndup(suffix
, b
);
808 if (!(r
= new(char, a
+b
+1)))
812 memcpy(r
+a
, suffix
, b
);
818 char *strappend(const char *s
, const char *suffix
) {
819 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
822 int readlink_malloc(const char *p
, char **r
) {
832 if (!(c
= new(char, l
)))
835 if ((n
= readlink(p
, c
, l
-1)) < 0) {
841 if ((size_t) n
< l
-1) {
852 int readlink_and_make_absolute(const char *p
, char **r
) {
859 if ((j
= readlink_malloc(p
, &target
)) < 0)
862 k
= file_in_same_dir(p
, target
);
872 int parent_of_path(const char *path
, char **_r
) {
873 const char *e
, *a
= NULL
, *b
= NULL
, *p
;
883 for (e
= path
; *e
; e
++) {
885 if (!slash
&& *e
== '/') {
889 } else if (slash
&& *e
!= '/')
904 r
= strndup(path
, p
-path
);
914 char *file_name_from_path(const char *p
) {
919 if ((r
= strrchr(p
, '/')))
925 bool path_is_absolute(const char *p
) {
931 bool is_path(const char *p
) {
933 return !!strchr(p
, '/');
936 char *path_make_absolute(const char *p
, const char *prefix
) {
941 /* Makes every item in the list an absolute path by prepending
942 * the prefix, if specified and necessary */
944 if (path_is_absolute(p
) || !prefix
)
947 if (asprintf(&r
, "%s/%s", prefix
, p
) < 0)
953 char *path_make_absolute_cwd(const char *p
) {
958 /* Similar to path_make_absolute(), but prefixes with the
959 * current working directory. */
961 if (path_is_absolute(p
))
964 if (!(cwd
= get_current_dir_name()))
967 r
= path_make_absolute(p
, cwd
);
973 char **strv_path_make_absolute_cwd(char **l
) {
976 /* Goes through every item in the string list and makes it
977 * absolute. This works in place and won't rollback any
978 * changes on failure. */
983 if (!(t
= path_make_absolute_cwd(*s
)))
993 char **strv_path_canonicalize(char **l
) {
1001 /* Goes through every item in the string list and canonicalize
1002 * the path. This works in place and won't rollback any
1003 * changes on failure. */
1005 STRV_FOREACH(s
, l
) {
1008 t
= path_make_absolute_cwd(*s
);
1017 u
= canonicalize_file_name(t
);
1021 if (errno
== ENOMEM
|| !errno
)
1038 int reset_all_signal_handlers(void) {
1041 for (sig
= 1; sig
< _NSIG
; sig
++) {
1042 struct sigaction sa
;
1044 if (sig
== SIGKILL
|| sig
== SIGSTOP
)
1048 sa
.sa_handler
= SIG_DFL
;
1049 sa
.sa_flags
= SA_RESTART
;
1051 /* On Linux the first two RT signals are reserved by
1052 * glibc, and sigaction() will return EINVAL for them. */
1053 if ((sigaction(sig
, &sa
, NULL
) < 0))
1054 if (errno
!= EINVAL
)
1061 char *strstrip(char *s
) {
1064 /* Drops trailing whitespace. Modifies the string in
1065 * place. Returns pointer to first non-space character */
1067 s
+= strspn(s
, WHITESPACE
);
1069 for (e
= s
; *e
; e
++)
1070 if (!strchr(WHITESPACE
, *e
))
1081 char *delete_chars(char *s
, const char *bad
) {
1084 /* Drops all whitespace, regardless where in the string */
1086 for (f
= s
, t
= s
; *f
; f
++) {
1087 if (strchr(bad
, *f
))
1098 char *file_in_same_dir(const char *path
, const char *filename
) {
1105 /* This removes the last component of path and appends
1106 * filename, unless the latter is absolute anyway or the
1109 if (path_is_absolute(filename
))
1110 return strdup(filename
);
1112 if (!(e
= strrchr(path
, '/')))
1113 return strdup(filename
);
1115 k
= strlen(filename
);
1116 if (!(r
= new(char, e
-path
+1+k
+1)))
1119 memcpy(r
, path
, e
-path
+1);
1120 memcpy(r
+(e
-path
)+1, filename
, k
+1);
1125 int safe_mkdir(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
1128 if (label_mkdir(path
, mode
) >= 0)
1129 if (chmod_and_chown(path
, mode
, uid
, gid
) < 0)
1132 if (lstat(path
, &st
) < 0)
1135 if ((st
.st_mode
& 0777) != mode
||
1138 !S_ISDIR(st
.st_mode
)) {
1147 int mkdir_parents(const char *path
, mode_t mode
) {
1152 /* Creates every parent directory in the path except the last
1155 p
= path
+ strspn(path
, "/");
1160 e
= p
+ strcspn(p
, "/");
1161 p
= e
+ strspn(e
, "/");
1163 /* Is this the last component? If so, then we're
1168 if (!(t
= strndup(path
, e
- path
)))
1171 r
= label_mkdir(t
, mode
);
1174 if (r
< 0 && errno
!= EEXIST
)
1179 int mkdir_p(const char *path
, mode_t mode
) {
1184 if ((r
= mkdir_parents(path
, mode
)) < 0)
1187 if (label_mkdir(path
, mode
) < 0 && errno
!= EEXIST
)
1193 int rmdir_parents(const char *path
, const char *stop
) {
1202 /* Skip trailing slashes */
1203 while (l
> 0 && path
[l
-1] == '/')
1209 /* Skip last component */
1210 while (l
> 0 && path
[l
-1] != '/')
1213 /* Skip trailing slashes */
1214 while (l
> 0 && path
[l
-1] == '/')
1220 if (!(t
= strndup(path
, l
)))
1223 if (path_startswith(stop
, t
)) {
1232 if (errno
!= ENOENT
)
1240 char hexchar(int x
) {
1241 static const char table
[16] = "0123456789abcdef";
1243 return table
[x
& 15];
1246 int unhexchar(char c
) {
1248 if (c
>= '0' && c
<= '9')
1251 if (c
>= 'a' && c
<= 'f')
1252 return c
- 'a' + 10;
1254 if (c
>= 'A' && c
<= 'F')
1255 return c
- 'A' + 10;
1260 char octchar(int x
) {
1261 return '0' + (x
& 7);
1264 int unoctchar(char c
) {
1266 if (c
>= '0' && c
<= '7')
1272 char decchar(int x
) {
1273 return '0' + (x
% 10);
1276 int undecchar(char c
) {
1278 if (c
>= '0' && c
<= '9')
1284 char *cescape(const char *s
) {
1290 /* Does C style string escaping. */
1292 if (!(r
= new(char, strlen(s
)*4 + 1)))
1295 for (f
= s
, t
= r
; *f
; f
++)
1341 /* For special chars we prefer octal over
1342 * hexadecimal encoding, simply because glib's
1343 * g_strescape() does the same */
1344 if ((*f
< ' ') || (*f
>= 127)) {
1346 *(t
++) = octchar((unsigned char) *f
>> 6);
1347 *(t
++) = octchar((unsigned char) *f
>> 3);
1348 *(t
++) = octchar((unsigned char) *f
);
1359 char *cunescape_length(const char *s
, size_t length
) {
1365 /* Undoes C style string escaping */
1367 if (!(r
= new(char, length
+1)))
1370 for (f
= s
, t
= r
; f
< s
+ length
; f
++) {
1413 /* This is an extension of the XDG syntax files */
1418 /* hexadecimal encoding */
1421 if ((a
= unhexchar(f
[1])) < 0 ||
1422 (b
= unhexchar(f
[2])) < 0) {
1423 /* Invalid escape code, let's take it literal then */
1427 *(t
++) = (char) ((a
<< 4) | b
);
1442 /* octal encoding */
1445 if ((a
= unoctchar(f
[0])) < 0 ||
1446 (b
= unoctchar(f
[1])) < 0 ||
1447 (c
= unoctchar(f
[2])) < 0) {
1448 /* Invalid escape code, let's take it literal then */
1452 *(t
++) = (char) ((a
<< 6) | (b
<< 3) | c
);
1460 /* premature end of string.*/
1465 /* Invalid escape code, let's take it literal then */
1477 char *cunescape(const char *s
) {
1478 return cunescape_length(s
, strlen(s
));
1481 char *xescape(const char *s
, const char *bad
) {
1485 /* Escapes all chars in bad, in addition to \ and all special
1486 * chars, in \xFF style escaping. May be reversed with
1489 if (!(r
= new(char, strlen(s
)*4+1)))
1492 for (f
= s
, t
= r
; *f
; f
++) {
1494 if ((*f
< ' ') || (*f
>= 127) ||
1495 (*f
== '\\') || strchr(bad
, *f
)) {
1498 *(t
++) = hexchar(*f
>> 4);
1499 *(t
++) = hexchar(*f
);
1509 char *bus_path_escape(const char *s
) {
1515 /* Escapes all chars that D-Bus' object path cannot deal
1516 * with. Can be reverse with bus_path_unescape() */
1518 if (!(r
= new(char, strlen(s
)*3+1)))
1521 for (f
= s
, t
= r
; *f
; f
++) {
1523 if (!(*f
>= 'A' && *f
<= 'Z') &&
1524 !(*f
>= 'a' && *f
<= 'z') &&
1525 !(*f
>= '0' && *f
<= '9')) {
1527 *(t
++) = hexchar(*f
>> 4);
1528 *(t
++) = hexchar(*f
);
1538 char *bus_path_unescape(const char *f
) {
1543 if (!(r
= strdup(f
)))
1546 for (t
= r
; *f
; f
++) {
1551 if ((a
= unhexchar(f
[1])) < 0 ||
1552 (b
= unhexchar(f
[2])) < 0) {
1553 /* Invalid escape code, let's take it literal then */
1556 *(t
++) = (char) ((a
<< 4) | b
);
1568 char *path_kill_slashes(char *path
) {
1572 /* Removes redundant inner and trailing slashes. Modifies the
1573 * passed string in-place.
1575 * ///foo///bar/ becomes /foo/bar
1578 for (f
= path
, t
= path
; *f
; f
++) {
1593 /* Special rule, if we are talking of the root directory, a
1594 trailing slash is good */
1596 if (t
== path
&& slash
)
1603 bool path_startswith(const char *path
, const char *prefix
) {
1607 if ((path
[0] == '/') != (prefix
[0] == '/'))
1613 path
+= strspn(path
, "/");
1614 prefix
+= strspn(prefix
, "/");
1622 a
= strcspn(path
, "/");
1623 b
= strcspn(prefix
, "/");
1628 if (memcmp(path
, prefix
, a
) != 0)
1636 bool path_equal(const char *a
, const char *b
) {
1640 if ((a
[0] == '/') != (b
[0] == '/'))
1646 a
+= strspn(a
, "/");
1647 b
+= strspn(b
, "/");
1649 if (*a
== 0 && *b
== 0)
1652 if (*a
== 0 || *b
== 0)
1655 j
= strcspn(a
, "/");
1656 k
= strcspn(b
, "/");
1661 if (memcmp(a
, b
, j
) != 0)
1669 char *ascii_strlower(char *t
) {
1674 for (p
= t
; *p
; p
++)
1675 if (*p
>= 'A' && *p
<= 'Z')
1676 *p
= *p
- 'A' + 'a';
1681 bool ignore_file(const char *filename
) {
1685 filename
[0] == '.' ||
1686 streq(filename
, "lost+found") ||
1687 streq(filename
, "aquota.user") ||
1688 streq(filename
, "aquota.group") ||
1689 endswith(filename
, "~") ||
1690 endswith(filename
, ".rpmnew") ||
1691 endswith(filename
, ".rpmsave") ||
1692 endswith(filename
, ".rpmorig") ||
1693 endswith(filename
, ".dpkg-old") ||
1694 endswith(filename
, ".dpkg-new") ||
1695 endswith(filename
, ".swp");
1698 int fd_nonblock(int fd
, bool nonblock
) {
1703 if ((flags
= fcntl(fd
, F_GETFL
, 0)) < 0)
1707 flags
|= O_NONBLOCK
;
1709 flags
&= ~O_NONBLOCK
;
1711 if (fcntl(fd
, F_SETFL
, flags
) < 0)
1717 int fd_cloexec(int fd
, bool cloexec
) {
1722 if ((flags
= fcntl(fd
, F_GETFD
, 0)) < 0)
1726 flags
|= FD_CLOEXEC
;
1728 flags
&= ~FD_CLOEXEC
;
1730 if (fcntl(fd
, F_SETFD
, flags
) < 0)
1736 int close_all_fds(const int except
[], unsigned n_except
) {
1741 if (!(d
= opendir("/proc/self/fd")))
1744 while ((de
= readdir(d
))) {
1747 if (ignore_file(de
->d_name
))
1750 if ((r
= safe_atoi(de
->d_name
, &fd
)) < 0)
1764 for (i
= 0; i
< n_except
; i
++)
1765 if (except
[i
] == fd
) {
1774 if ((r
= close_nointr(fd
)) < 0) {
1775 /* Valgrind has its own FD and doesn't want to have it closed */
1788 bool chars_intersect(const char *a
, const char *b
) {
1791 /* Returns true if any of the chars in a are in b. */
1792 for (p
= a
; *p
; p
++)
1799 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
1809 sec
= (time_t) (t
/ USEC_PER_SEC
);
1811 if (strftime(buf
, l
, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec
, &tm
)) <= 0)
1817 char *format_timestamp_pretty(char *buf
, size_t l
, usec_t t
) {
1820 n
= now(CLOCK_REALTIME
);
1822 if (t
<= 0 || t
> n
|| t
+ USEC_PER_DAY
*7 <= t
)
1827 if (d
>= USEC_PER_YEAR
)
1828 snprintf(buf
, l
, "%llu years and %llu months ago",
1829 (unsigned long long) (d
/ USEC_PER_YEAR
),
1830 (unsigned long long) ((d
% USEC_PER_YEAR
) / USEC_PER_MONTH
));
1831 else if (d
>= USEC_PER_MONTH
)
1832 snprintf(buf
, l
, "%llu months and %llu days ago",
1833 (unsigned long long) (d
/ USEC_PER_MONTH
),
1834 (unsigned long long) ((d
% USEC_PER_MONTH
) / USEC_PER_DAY
));
1835 else if (d
>= USEC_PER_WEEK
)
1836 snprintf(buf
, l
, "%llu weeks and %llu days ago",
1837 (unsigned long long) (d
/ USEC_PER_WEEK
),
1838 (unsigned long long) ((d
% USEC_PER_WEEK
) / USEC_PER_DAY
));
1839 else if (d
>= 2*USEC_PER_DAY
)
1840 snprintf(buf
, l
, "%llu days ago", (unsigned long long) (d
/ USEC_PER_DAY
));
1841 else if (d
>= 25*USEC_PER_HOUR
)
1842 snprintf(buf
, l
, "1 day and %lluh ago",
1843 (unsigned long long) ((d
- USEC_PER_DAY
) / USEC_PER_HOUR
));
1844 else if (d
>= 6*USEC_PER_HOUR
)
1845 snprintf(buf
, l
, "%lluh ago",
1846 (unsigned long long) (d
/ USEC_PER_HOUR
));
1847 else if (d
>= USEC_PER_HOUR
)
1848 snprintf(buf
, l
, "%lluh %llumin ago",
1849 (unsigned long long) (d
/ USEC_PER_HOUR
),
1850 (unsigned long long) ((d
% USEC_PER_HOUR
) / USEC_PER_MINUTE
));
1851 else if (d
>= 5*USEC_PER_MINUTE
)
1852 snprintf(buf
, l
, "%llumin ago",
1853 (unsigned long long) (d
/ USEC_PER_MINUTE
));
1854 else if (d
>= USEC_PER_MINUTE
)
1855 snprintf(buf
, l
, "%llumin %llus ago",
1856 (unsigned long long) (d
/ USEC_PER_MINUTE
),
1857 (unsigned long long) ((d
% USEC_PER_MINUTE
) / USEC_PER_SEC
));
1858 else if (d
>= USEC_PER_SEC
)
1859 snprintf(buf
, l
, "%llus ago",
1860 (unsigned long long) (d
/ USEC_PER_SEC
));
1861 else if (d
>= USEC_PER_MSEC
)
1862 snprintf(buf
, l
, "%llums ago",
1863 (unsigned long long) (d
/ USEC_PER_MSEC
));
1865 snprintf(buf
, l
, "%lluus ago",
1866 (unsigned long long) d
);
1868 snprintf(buf
, l
, "now");
1874 char *format_timespan(char *buf
, size_t l
, usec_t t
) {
1875 static const struct {
1879 { "w", USEC_PER_WEEK
},
1880 { "d", USEC_PER_DAY
},
1881 { "h", USEC_PER_HOUR
},
1882 { "min", USEC_PER_MINUTE
},
1883 { "s", USEC_PER_SEC
},
1884 { "ms", USEC_PER_MSEC
},
1894 if (t
== (usec_t
) -1)
1898 snprintf(p
, l
, "0");
1903 /* The result of this function can be parsed with parse_usec */
1905 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
1909 if (t
< table
[i
].usec
)
1915 k
= snprintf(p
, l
, "%s%llu%s", p
> buf
? " " : "", (unsigned long long) (t
/ table
[i
].usec
), table
[i
].suffix
);
1916 n
= MIN((size_t) k
, l
);
1929 bool fstype_is_network(const char *fstype
) {
1930 static const char * const table
[] = {
1942 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
1943 if (streq(table
[i
], fstype
))
1952 if ((fd
= open("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
)) < 0)
1957 TIOCL_GETKMSGREDIRECT
,
1961 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0)
1964 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
1967 if (ioctl(fd
, VT_ACTIVATE
, vt
) < 0)
1970 close_nointr_nofail(r
);
1974 int read_one_char(FILE *f
, char *ret
, bool *need_nl
) {
1975 struct termios old_termios
, new_termios
;
1982 if (tcgetattr(fileno(f
), &old_termios
) >= 0) {
1983 new_termios
= old_termios
;
1985 new_termios
.c_lflag
&= ~ICANON
;
1986 new_termios
.c_cc
[VMIN
] = 1;
1987 new_termios
.c_cc
[VTIME
] = 0;
1989 if (tcsetattr(fileno(f
), TCSADRAIN
, &new_termios
) >= 0) {
1992 k
= fread(&c
, 1, 1, f
);
1994 tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
2000 *need_nl
= c
!= '\n';
2007 if (!(fgets(line
, sizeof(line
), f
)))
2012 if (strlen(line
) != 1)
2022 int ask(char *ret
, const char *replies
, const char *text
, ...) {
2029 on_tty
= isatty(STDOUT_FILENO
);
2035 bool need_nl
= true;
2038 fputs("\x1B[1m", stdout
);
2045 fputs("\x1B[0m", stdout
);
2049 if ((r
= read_one_char(stdin
, &c
, &need_nl
)) < 0) {
2051 if (r
== -EBADMSG
) {
2052 puts("Bad input, please try again.");
2063 if (strchr(replies
, c
)) {
2068 puts("Read unexpected character, please try again.");
2072 int reset_terminal(int fd
) {
2073 struct termios termios
;
2077 /* Set terminal to some sane defaults */
2081 /* We leave locked terminal attributes untouched, so that
2082 * Plymouth may set whatever it wants to set, and we don't
2083 * interfere with that. */
2085 /* Disable exclusive mode, just in case */
2086 ioctl(fd
, TIOCNXCL
);
2088 /* Enable console unicode mode */
2090 ioctl(fd
, KDSKBMODE
, &arg
);
2092 if (tcgetattr(fd
, &termios
) < 0) {
2097 /* We only reset the stuff that matters to the software. How
2098 * hardware is set up we don't touch assuming that somebody
2099 * else will do that for us */
2101 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
2102 termios
.c_iflag
|= ICRNL
| IMAXBEL
| IUTF8
;
2103 termios
.c_oflag
|= ONLCR
;
2104 termios
.c_cflag
|= CREAD
;
2105 termios
.c_lflag
= ISIG
| ICANON
| IEXTEN
| ECHO
| ECHOE
| ECHOK
| ECHOCTL
| ECHOPRT
| ECHOKE
;
2107 termios
.c_cc
[VINTR
] = 03; /* ^C */
2108 termios
.c_cc
[VQUIT
] = 034; /* ^\ */
2109 termios
.c_cc
[VERASE
] = 0177;
2110 termios
.c_cc
[VKILL
] = 025; /* ^X */
2111 termios
.c_cc
[VEOF
] = 04; /* ^D */
2112 termios
.c_cc
[VSTART
] = 021; /* ^Q */
2113 termios
.c_cc
[VSTOP
] = 023; /* ^S */
2114 termios
.c_cc
[VSUSP
] = 032; /* ^Z */
2115 termios
.c_cc
[VLNEXT
] = 026; /* ^V */
2116 termios
.c_cc
[VWERASE
] = 027; /* ^W */
2117 termios
.c_cc
[VREPRINT
] = 022; /* ^R */
2118 termios
.c_cc
[VEOL
] = 0;
2119 termios
.c_cc
[VEOL2
] = 0;
2121 termios
.c_cc
[VTIME
] = 0;
2122 termios
.c_cc
[VMIN
] = 1;
2124 if (tcsetattr(fd
, TCSANOW
, &termios
) < 0)
2128 /* Just in case, flush all crap out */
2129 tcflush(fd
, TCIOFLUSH
);
2134 int open_terminal(const char *name
, int mode
) {
2137 if ((fd
= open(name
, mode
)) < 0)
2140 if ((r
= isatty(fd
)) < 0) {
2141 close_nointr_nofail(fd
);
2146 close_nointr_nofail(fd
);
2153 int flush_fd(int fd
) {
2154 struct pollfd pollfd
;
2158 pollfd
.events
= POLLIN
;
2165 if ((r
= poll(&pollfd
, 1, 0)) < 0) {
2176 if ((l
= read(fd
, buf
, sizeof(buf
))) < 0) {
2181 if (errno
== EAGAIN
)
2192 int acquire_terminal(const char *name
, bool fail
, bool force
, bool ignore_tiocstty_eperm
) {
2193 int fd
= -1, notify
= -1, r
, wd
= -1;
2197 /* We use inotify to be notified when the tty is closed. We
2198 * create the watch before checking if we can actually acquire
2199 * it, so that we don't lose any event.
2201 * Note: strictly speaking this actually watches for the
2202 * device being closed, it does *not* really watch whether a
2203 * tty loses its controlling process. However, unless some
2204 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2205 * its tty otherwise this will not become a problem. As long
2206 * as the administrator makes sure not configure any service
2207 * on the same tty as an untrusted user this should not be a
2208 * problem. (Which he probably should not do anyway.) */
2210 if (!fail
&& !force
) {
2211 if ((notify
= inotify_init1(IN_CLOEXEC
)) < 0) {
2216 if ((wd
= inotify_add_watch(notify
, name
, IN_CLOSE
)) < 0) {
2224 if ((r
= flush_fd(notify
)) < 0)
2227 /* We pass here O_NOCTTY only so that we can check the return
2228 * value TIOCSCTTY and have a reliable way to figure out if we
2229 * successfully became the controlling process of the tty */
2230 if ((fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
)) < 0)
2233 /* First, try to get the tty */
2234 r
= ioctl(fd
, TIOCSCTTY
, force
);
2236 /* Sometimes it makes sense to ignore TIOCSCTTY
2237 * returning EPERM, i.e. when very likely we already
2238 * are have this controlling terminal. */
2239 if (r
< 0 && errno
== EPERM
&& ignore_tiocstty_eperm
)
2242 if (r
< 0 && (force
|| fail
|| errno
!= EPERM
)) {
2252 assert(notify
>= 0);
2255 uint8_t inotify_buffer
[sizeof(struct inotify_event
) + FILENAME_MAX
];
2257 struct inotify_event
*e
;
2259 if ((l
= read(notify
, &inotify_buffer
, sizeof(inotify_buffer
))) < 0) {
2268 e
= (struct inotify_event
*) inotify_buffer
;
2273 if (e
->wd
!= wd
|| !(e
->mask
& IN_CLOSE
)) {
2278 step
= sizeof(struct inotify_event
) + e
->len
;
2279 assert(step
<= (size_t) l
);
2281 e
= (struct inotify_event
*) ((uint8_t*) e
+ step
);
2288 /* We close the tty fd here since if the old session
2289 * ended our handle will be dead. It's important that
2290 * we do this after sleeping, so that we don't enter
2291 * an endless loop. */
2292 close_nointr_nofail(fd
);
2296 close_nointr_nofail(notify
);
2298 if ((r
= reset_terminal(fd
)) < 0)
2299 log_warning("Failed to reset terminal: %s", strerror(-r
));
2305 close_nointr_nofail(fd
);
2308 close_nointr_nofail(notify
);
2313 int release_terminal(void) {
2315 struct sigaction sa_old
, sa_new
;
2317 if ((fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_NDELAY
)) < 0)
2320 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2321 * by our own TIOCNOTTY */
2324 sa_new
.sa_handler
= SIG_IGN
;
2325 sa_new
.sa_flags
= SA_RESTART
;
2326 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
2328 if (ioctl(fd
, TIOCNOTTY
) < 0)
2331 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
2333 close_nointr_nofail(fd
);
2337 int sigaction_many(const struct sigaction
*sa
, ...) {
2342 while ((sig
= va_arg(ap
, int)) > 0)
2343 if (sigaction(sig
, sa
, NULL
) < 0)
2350 int ignore_signals(int sig
, ...) {
2351 struct sigaction sa
;
2356 sa
.sa_handler
= SIG_IGN
;
2357 sa
.sa_flags
= SA_RESTART
;
2359 if (sigaction(sig
, &sa
, NULL
) < 0)
2363 while ((sig
= va_arg(ap
, int)) > 0)
2364 if (sigaction(sig
, &sa
, NULL
) < 0)
2371 int default_signals(int sig
, ...) {
2372 struct sigaction sa
;
2377 sa
.sa_handler
= SIG_DFL
;
2378 sa
.sa_flags
= SA_RESTART
;
2380 if (sigaction(sig
, &sa
, NULL
) < 0)
2384 while ((sig
= va_arg(ap
, int)) > 0)
2385 if (sigaction(sig
, &sa
, NULL
) < 0)
2392 int close_pipe(int p
[]) {
2398 a
= close_nointr(p
[0]);
2403 b
= close_nointr(p
[1]);
2407 return a
< 0 ? a
: b
;
2410 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2419 while (nbytes
> 0) {
2422 if ((k
= read(fd
, p
, nbytes
)) <= 0) {
2424 if (k
< 0 && errno
== EINTR
)
2427 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2428 struct pollfd pollfd
;
2432 pollfd
.events
= POLLIN
;
2434 if (poll(&pollfd
, 1, -1) < 0) {
2438 return n
> 0 ? n
: -errno
;
2441 if (pollfd
.revents
!= POLLIN
)
2442 return n
> 0 ? n
: -EIO
;
2447 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2458 ssize_t
loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2467 while (nbytes
> 0) {
2470 if ((k
= write(fd
, p
, nbytes
)) <= 0) {
2472 if (k
< 0 && errno
== EINTR
)
2475 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2476 struct pollfd pollfd
;
2480 pollfd
.events
= POLLOUT
;
2482 if (poll(&pollfd
, 1, -1) < 0) {
2486 return n
> 0 ? n
: -errno
;
2489 if (pollfd
.revents
!= POLLOUT
)
2490 return n
> 0 ? n
: -EIO
;
2495 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2506 int path_is_mount_point(const char *t
) {
2511 if (lstat(t
, &a
) < 0) {
2512 if (errno
== ENOENT
)
2518 if ((r
= parent_of_path(t
, &parent
)) < 0)
2521 r
= lstat(parent
, &b
);
2527 return a
.st_dev
!= b
.st_dev
;
2530 int parse_usec(const char *t
, usec_t
*usec
) {
2531 static const struct {
2535 { "sec", USEC_PER_SEC
},
2536 { "s", USEC_PER_SEC
},
2537 { "min", USEC_PER_MINUTE
},
2538 { "hr", USEC_PER_HOUR
},
2539 { "h", USEC_PER_HOUR
},
2540 { "d", USEC_PER_DAY
},
2541 { "w", USEC_PER_WEEK
},
2542 { "msec", USEC_PER_MSEC
},
2543 { "ms", USEC_PER_MSEC
},
2544 { "m", USEC_PER_MINUTE
},
2547 { "", USEC_PER_SEC
},
2563 l
= strtoll(p
, &e
, 10);
2574 e
+= strspn(e
, WHITESPACE
);
2576 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
2577 if (startswith(e
, table
[i
].suffix
)) {
2578 r
+= (usec_t
) l
* table
[i
].usec
;
2579 p
= e
+ strlen(table
[i
].suffix
);
2583 if (i
>= ELEMENTSOF(table
))
2593 int make_stdio(int fd
) {
2598 r
= dup2(fd
, STDIN_FILENO
);
2599 s
= dup2(fd
, STDOUT_FILENO
);
2600 t
= dup2(fd
, STDERR_FILENO
);
2603 close_nointr_nofail(fd
);
2605 if (r
< 0 || s
< 0 || t
< 0)
2611 int make_null_stdio(void) {
2614 if ((null_fd
= open("/dev/null", O_RDWR
|O_NOCTTY
)) < 0)
2617 return make_stdio(null_fd
);
2620 bool is_clean_exit(int code
, int status
) {
2622 if (code
== CLD_EXITED
)
2625 /* If a daemon does not implement handlers for some of the
2626 * signals that's not considered an unclean shutdown */
2627 if (code
== CLD_KILLED
)
2631 status
== SIGTERM
||
2637 bool is_clean_exit_lsb(int code
, int status
) {
2639 if (is_clean_exit(code
, status
))
2643 code
== CLD_EXITED
&&
2644 (status
== EXIT_NOTINSTALLED
|| status
== EXIT_NOTCONFIGURED
);
2647 bool is_device_path(const char *path
) {
2649 /* Returns true on paths that refer to a device, either in
2650 * sysfs or in /dev */
2653 path_startswith(path
, "/dev/") ||
2654 path_startswith(path
, "/sys/");
2657 int dir_is_empty(const char *path
) {
2660 struct dirent buf
, *de
;
2662 if (!(d
= opendir(path
)))
2666 if ((r
= readdir_r(d
, &buf
, &de
)) > 0) {
2676 if (!ignore_file(de
->d_name
)) {
2686 unsigned long long random_ull(void) {
2691 if ((fd
= open("/dev/urandom", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
)) < 0)
2694 r
= loop_read(fd
, &ull
, sizeof(ull
), true);
2695 close_nointr_nofail(fd
);
2697 if (r
!= sizeof(ull
))
2703 return random() * RAND_MAX
+ random();
2706 void rename_process(const char name
[8]) {
2709 prctl(PR_SET_NAME
, name
);
2711 /* This is a like a poor man's setproctitle(). The string
2712 * passed should fit in 7 chars (i.e. the length of
2715 if (program_invocation_name
)
2716 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2719 void sigset_add_many(sigset_t
*ss
, ...) {
2726 while ((sig
= va_arg(ap
, int)) > 0)
2727 assert_se(sigaddset(ss
, sig
) == 0);
2731 char* gethostname_malloc(void) {
2734 assert_se(uname(&u
) >= 0);
2737 return strdup(u
.nodename
);
2739 return strdup(u
.sysname
);
2742 char* getlogname_malloc(void) {
2746 struct passwd pwbuf
, *pw
= NULL
;
2749 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2754 /* Shortcut things to avoid NSS lookups */
2756 return strdup("root");
2758 if ((bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
)) <= 0)
2761 if (!(buf
= malloc(bufsize
)))
2764 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
) {
2765 name
= strdup(pw
->pw_name
);
2772 if (asprintf(&name
, "%lu", (unsigned long) uid
) < 0)
2778 int getttyname_malloc(char **r
) {
2779 char path
[PATH_MAX
], *p
, *c
;
2784 if ((k
= ttyname_r(STDIN_FILENO
, path
, sizeof(path
))) != 0)
2790 if (startswith(path
, "/dev/"))
2793 if (!(c
= strdup(p
)))
2800 static int rm_rf_children(int fd
, bool only_dirs
) {
2806 /* This returns the first error we run into, but nevertheless
2809 if (!(d
= fdopendir(fd
))) {
2810 close_nointr_nofail(fd
);
2812 return errno
== ENOENT
? 0 : -errno
;
2816 struct dirent buf
, *de
;
2820 if ((r
= readdir_r(d
, &buf
, &de
)) != 0) {
2829 if (streq(de
->d_name
, ".") || streq(de
->d_name
, ".."))
2832 if (de
->d_type
== DT_UNKNOWN
) {
2835 if (fstatat(fd
, de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0) {
2836 if (ret
== 0 && errno
!= ENOENT
)
2841 is_dir
= S_ISDIR(st
.st_mode
);
2843 is_dir
= de
->d_type
== DT_DIR
;
2848 if ((subdir_fd
= openat(fd
, de
->d_name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
)) < 0) {
2849 if (ret
== 0 && errno
!= ENOENT
)
2854 if ((r
= rm_rf_children(subdir_fd
, only_dirs
)) < 0) {
2859 if (unlinkat(fd
, de
->d_name
, AT_REMOVEDIR
) < 0) {
2860 if (ret
== 0 && errno
!= ENOENT
)
2863 } else if (!only_dirs
) {
2865 if (unlinkat(fd
, de
->d_name
, 0) < 0) {
2866 if (ret
== 0 && errno
!= ENOENT
)
2877 int rm_rf(const char *path
, bool only_dirs
, bool delete_root
) {
2883 if ((fd
= open(path
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
)) < 0) {
2885 if (errno
!= ENOTDIR
)
2888 if (delete_root
&& !only_dirs
)
2889 if (unlink(path
) < 0)
2895 r
= rm_rf_children(fd
, only_dirs
);
2898 if (rmdir(path
) < 0) {
2906 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2909 /* Under the assumption that we are running privileged we
2910 * first change the access mode and only then hand out
2911 * ownership to avoid a window where access is too open. */
2913 if (chmod(path
, mode
) < 0)
2916 if (chown(path
, uid
, gid
) < 0)
2922 cpu_set_t
* cpu_set_malloc(unsigned *ncpus
) {
2926 /* Allocates the cpuset in the right size */
2929 if (!(r
= CPU_ALLOC(n
)))
2932 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), r
) >= 0) {
2933 CPU_ZERO_S(CPU_ALLOC_SIZE(n
), r
);
2943 if (errno
!= EINVAL
)
2950 void status_vprintf(const char *format
, va_list ap
) {
2956 /* This independent of logging, as status messages are
2957 * optional and go exclusively to the console. */
2959 if (vasprintf(&s
, format
, ap
) < 0)
2962 if ((fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
)) < 0)
2965 write(fd
, s
, strlen(s
));
2971 close_nointr_nofail(fd
);
2974 void status_printf(const char *format
, ...) {
2979 va_start(ap
, format
);
2980 status_vprintf(format
, ap
);
2984 void status_welcome(void) {
2985 char *pretty_name
= NULL
, *ansi_color
= NULL
;
2986 const char *const_pretty
= NULL
, *const_color
= NULL
;
2989 if ((r
= parse_env_file("/etc/os-release", NEWLINE
,
2990 "PRETTY_NAME", &pretty_name
,
2991 "ANSI_COLOR", &ansi_color
,
2995 log_warning("Failed to read /etc/os-release: %s", strerror(-r
));
2998 #if defined(TARGET_FEDORA)
3000 if ((r
= read_one_line_file("/etc/system-release", &pretty_name
)) < 0) {
3003 log_warning("Failed to read /etc/system-release: %s", strerror(-r
));
3005 truncate_nl(pretty_name
);
3008 if (!ansi_color
&& pretty_name
) {
3010 /* This tries to mimic the color magic the old Red Hat sysinit
3013 if (startswith(pretty_name
, "Red Hat"))
3014 const_color
= "0;31"; /* Red for RHEL */
3015 else if (startswith(pretty_name
, "Fedora"))
3016 const_color
= "0;34"; /* Blue for Fedora */
3019 #elif defined(TARGET_SUSE)
3022 if ((r
= read_one_line_file("/etc/SuSE-release", &pretty_name
)) < 0) {
3025 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r
));
3027 truncate_nl(pretty_name
);
3031 const_color
= "0;32"; /* Green for openSUSE */
3033 #elif defined(TARGET_GENTOO)
3036 if ((r
= read_one_line_file("/etc/gentoo-release", &pretty_name
)) < 0) {
3039 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r
));
3041 truncate_nl(pretty_name
);
3045 const_color
= "1;34"; /* Light Blue for Gentoo */
3047 #elif defined(TARGET_DEBIAN)
3052 if ((r
= read_one_line_file("/etc/debian_version", &version
)) < 0) {
3055 log_warning("Failed to read /etc/debian_version: %s", strerror(-r
));
3057 truncate_nl(version
);
3058 pretty_name
= strappend("Debian ", version
);
3062 log_warning("Failed to allocate Debian version string.");
3067 const_color
= "1;31"; /* Light Red for Debian */
3069 #elif defined(TARGET_UBUNTU)
3071 if ((r
= parse_env_file("/etc/lsb-release", NEWLINE
,
3072 "DISTRIB_DESCRIPTION", &pretty_name
,
3076 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r
));
3080 const_color
= "0;33"; /* Orange/Brown for Ubuntu */
3084 if (!pretty_name
&& !const_pretty
)
3085 const_pretty
= "Linux";
3087 if (!ansi_color
&& !const_color
)
3090 status_printf("Welcome to \x1B[%sm%s\x1B[0m!\n",
3091 const_color
? const_color
: ansi_color
,
3092 const_pretty
? const_pretty
: pretty_name
);
3095 char *replace_env(const char *format
, char **env
) {
3102 const char *e
, *word
= format
;
3107 for (e
= format
; *e
; e
++) {
3118 if (!(k
= strnappend(r
, word
, e
-word
-1)))
3127 } else if (*e
== '$') {
3128 if (!(k
= strnappend(r
, word
, e
-word
)))
3144 if (!(t
= strv_env_get_with_length(env
, word
+2, e
-word
-2)))
3147 if (!(k
= strappend(r
, t
)))
3160 if (!(k
= strnappend(r
, word
, e
-word
)))
3171 char **replace_env_argv(char **argv
, char **env
) {
3173 unsigned k
= 0, l
= 0;
3175 l
= strv_length(argv
);
3177 if (!(r
= new(char*, l
+1)))
3180 STRV_FOREACH(i
, argv
) {
3182 /* If $FOO appears as single word, replace it by the split up variable */
3183 if ((*i
)[0] == '$' && (*i
)[1] != '{') {
3188 if ((e
= strv_env_get(env
, *i
+1))) {
3190 if (!(m
= strv_split_quoted(e
))) {
3201 if (!(w
= realloc(r
, sizeof(char*) * (l
+1)))) {
3210 memcpy(r
+ k
, m
, q
* sizeof(char*));
3218 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3219 if (!(r
[k
++] = replace_env(*i
, env
))) {
3230 static __thread
int parsed_columns
= 0;
3233 if (parsed_columns
> 0)
3234 return parsed_columns
;
3236 if ((e
= getenv("COLUMNS")))
3237 parsed_columns
= atoi(e
);
3239 if (parsed_columns
<= 0) {
3243 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &ws
) >= 0)
3244 parsed_columns
= ws
.ws_col
;
3247 if (parsed_columns
<= 0)
3248 parsed_columns
= 80;
3250 return parsed_columns
;
3253 int running_in_chroot(void) {
3259 /* Only works as root */
3261 if (stat("/proc/1/root", &a
) < 0)
3264 if (stat("/", &b
) < 0)
3268 a
.st_dev
!= b
.st_dev
||
3269 a
.st_ino
!= b
.st_ino
;
3272 char *ellipsize(const char *s
, unsigned length
, unsigned percent
) {
3277 assert(percent
<= 100);
3278 assert(length
>= 3);
3282 if (l
<= 3 || l
<= length
)
3285 if (!(r
= new0(char, length
+1)))
3288 x
= (length
* percent
) / 100;
3298 s
+ l
- (length
- x
- 3),
3304 int touch(const char *path
) {
3309 if ((fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, 0666)) < 0)
3312 close_nointr_nofail(fd
);
3316 char *unquote(const char *s
, const char* quotes
) {
3320 if ((l
= strlen(s
)) < 2)
3323 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
3324 return strndup(s
+1, l
-2);
3329 int wait_for_terminate(pid_t pid
, siginfo_t
*status
) {
3336 if (waitid(P_PID
, pid
, status
, WEXITED
) < 0) {
3348 int wait_for_terminate_and_warn(const char *name
, pid_t pid
) {
3355 if ((r
= wait_for_terminate(pid
, &status
)) < 0) {
3356 log_warning("Failed to wait for %s: %s", name
, strerror(-r
));
3360 if (status
.si_code
== CLD_EXITED
) {
3361 if (status
.si_status
!= 0) {
3362 log_warning("%s failed with error code %i.", name
, status
.si_status
);
3366 log_debug("%s succeeded.", name
);
3369 } else if (status
.si_code
== CLD_KILLED
||
3370 status
.si_code
== CLD_DUMPED
) {
3372 log_warning("%s terminated by signal %s.", name
, signal_to_string(status
.si_status
));
3376 log_warning("%s failed due to unknown reason.", name
);
3388 bool null_or_empty(struct stat
*st
) {
3391 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
3394 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
3400 DIR *xopendirat(int fd
, const char *name
, int flags
) {
3401 return fdopendir(openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
));
3404 int signal_from_string_try_harder(const char *s
) {
3408 if ((signo
= signal_from_string(s
)) <= 0)
3409 if (startswith(s
, "SIG"))
3410 return signal_from_string(s
+3);
3415 void dual_timestamp_serialize(FILE *f
, const char *name
, dual_timestamp
*t
) {
3421 if (!dual_timestamp_is_set(t
))
3424 fprintf(f
, "%s=%llu %llu\n",
3426 (unsigned long long) t
->realtime
,
3427 (unsigned long long) t
->monotonic
);
3430 void dual_timestamp_deserialize(const char *value
, dual_timestamp
*t
) {
3431 unsigned long long a
, b
;
3436 if (sscanf(value
, "%lli %llu", &a
, &b
) != 2)
3437 log_debug("Failed to parse finish timestamp value %s", value
);
3444 char *fstab_node_to_udev_node(const char *p
) {
3448 /* FIXME: to follow udev's logic 100% we need to leave valid
3449 * UTF8 chars unescaped */
3451 if (startswith(p
, "LABEL=")) {
3453 if (!(u
= unquote(p
+6, "\"\'")))
3456 t
= xescape(u
, "/ ");
3462 r
= asprintf(&dn
, "/dev/disk/by-label/%s", t
);
3471 if (startswith(p
, "UUID=")) {
3473 if (!(u
= unquote(p
+5, "\"\'")))
3476 t
= xescape(u
, "/ ");
3482 r
= asprintf(&dn
, "/dev/disk/by-uuid/%s", ascii_strlower(t
));
3494 void filter_environ(const char *prefix
) {
3501 for (i
= 0, j
= 0; environ
[i
]; i
++) {
3503 if (startswith(environ
[i
], prefix
))
3506 environ
[j
++] = environ
[i
];
3512 const char *default_term_for_tty(const char *tty
) {
3515 if (startswith(tty
, "/dev/"))
3518 if (startswith(tty
, "tty") &&
3519 tty
[3] >= '0' && tty
[3] <= '9')
3520 return "TERM=linux";
3522 /* FIXME: Proper handling of /dev/console would be cool */
3524 return "TERM=vt100";
3527 static const char *const ioprio_class_table
[] = {
3528 [IOPRIO_CLASS_NONE
] = "none",
3529 [IOPRIO_CLASS_RT
] = "realtime",
3530 [IOPRIO_CLASS_BE
] = "best-effort",
3531 [IOPRIO_CLASS_IDLE
] = "idle"
3534 DEFINE_STRING_TABLE_LOOKUP(ioprio_class
, int);
3536 static const char *const sigchld_code_table
[] = {
3537 [CLD_EXITED
] = "exited",
3538 [CLD_KILLED
] = "killed",
3539 [CLD_DUMPED
] = "dumped",
3540 [CLD_TRAPPED
] = "trapped",
3541 [CLD_STOPPED
] = "stopped",
3542 [CLD_CONTINUED
] = "continued",
3545 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
3547 static const char *const log_facility_table
[LOG_NFACILITIES
] = {
3548 [LOG_FAC(LOG_KERN
)] = "kern",
3549 [LOG_FAC(LOG_USER
)] = "user",
3550 [LOG_FAC(LOG_MAIL
)] = "mail",
3551 [LOG_FAC(LOG_DAEMON
)] = "daemon",
3552 [LOG_FAC(LOG_AUTH
)] = "auth",
3553 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
3554 [LOG_FAC(LOG_LPR
)] = "lpr",
3555 [LOG_FAC(LOG_NEWS
)] = "news",
3556 [LOG_FAC(LOG_UUCP
)] = "uucp",
3557 [LOG_FAC(LOG_CRON
)] = "cron",
3558 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
3559 [LOG_FAC(LOG_FTP
)] = "ftp",
3560 [LOG_FAC(LOG_LOCAL0
)] = "local0",
3561 [LOG_FAC(LOG_LOCAL1
)] = "local1",
3562 [LOG_FAC(LOG_LOCAL2
)] = "local2",
3563 [LOG_FAC(LOG_LOCAL3
)] = "local3",
3564 [LOG_FAC(LOG_LOCAL4
)] = "local4",
3565 [LOG_FAC(LOG_LOCAL5
)] = "local5",
3566 [LOG_FAC(LOG_LOCAL6
)] = "local6",
3567 [LOG_FAC(LOG_LOCAL7
)] = "local7"
3570 DEFINE_STRING_TABLE_LOOKUP(log_facility
, int);
3572 static const char *const log_level_table
[] = {
3573 [LOG_EMERG
] = "emerg",
3574 [LOG_ALERT
] = "alert",
3575 [LOG_CRIT
] = "crit",
3577 [LOG_WARNING
] = "warning",
3578 [LOG_NOTICE
] = "notice",
3579 [LOG_INFO
] = "info",
3580 [LOG_DEBUG
] = "debug"
3583 DEFINE_STRING_TABLE_LOOKUP(log_level
, int);
3585 static const char* const sched_policy_table
[] = {
3586 [SCHED_OTHER
] = "other",
3587 [SCHED_BATCH
] = "batch",
3588 [SCHED_IDLE
] = "idle",
3589 [SCHED_FIFO
] = "fifo",
3593 DEFINE_STRING_TABLE_LOOKUP(sched_policy
, int);
3595 static const char* const rlimit_table
[] = {
3596 [RLIMIT_CPU
] = "LimitCPU",
3597 [RLIMIT_FSIZE
] = "LimitFSIZE",
3598 [RLIMIT_DATA
] = "LimitDATA",
3599 [RLIMIT_STACK
] = "LimitSTACK",
3600 [RLIMIT_CORE
] = "LimitCORE",
3601 [RLIMIT_RSS
] = "LimitRSS",
3602 [RLIMIT_NOFILE
] = "LimitNOFILE",
3603 [RLIMIT_AS
] = "LimitAS",
3604 [RLIMIT_NPROC
] = "LimitNPROC",
3605 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
3606 [RLIMIT_LOCKS
] = "LimitLOCKS",
3607 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
3608 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
3609 [RLIMIT_NICE
] = "LimitNICE",
3610 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
3611 [RLIMIT_RTTIME
] = "LimitRTTIME"
3614 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
3616 static const char* const ip_tos_table
[] = {
3617 [IPTOS_LOWDELAY
] = "low-delay",
3618 [IPTOS_THROUGHPUT
] = "throughput",
3619 [IPTOS_RELIABILITY
] = "reliability",
3620 [IPTOS_LOWCOST
] = "low-cost",
3623 DEFINE_STRING_TABLE_LOOKUP(ip_tos
, int);
3625 static const char *const signal_table
[] = {
3642 [SIGSTKFLT
] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3653 [SIGVTALRM
] = "VTALRM",
3655 [SIGWINCH
] = "WINCH",
3661 DEFINE_STRING_TABLE_LOOKUP(signal
, int);