]>
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) {
504 int read_one_line_file(const char *fn
, char **line
) {
507 char t
[LINE_MAX
], *c
;
512 if (!(f
= fopen(fn
, "re")))
515 if (!(fgets(t
, sizeof(t
), f
))) {
520 if (!(c
= strdup(t
))) {
533 int read_full_file(const char *fn
, char **contents
) {
540 if (!(f
= fopen(fn
, "re")))
543 if (fstat(fileno(f
), &st
) < 0) {
548 n
= st
.st_size
> 0 ? st
.st_size
: LINE_MAX
;
555 if (!(t
= realloc(buf
, n
+1))) {
561 k
= fread(buf
+ l
, 1, n
- l
, f
);
576 if (n
> 4*1024*1024) {
584 else if (!(buf
= calloc(1, 1))) {
603 const char *separator
, ...) {
611 if ((r
= read_full_file(fname
, &contents
)) < 0)
616 const char *key
= NULL
;
618 p
+= strspn(p
, separator
);
619 p
+= strspn(p
, WHITESPACE
);
624 if (!strchr(COMMENTS
, *p
)) {
628 va_start(ap
, separator
);
629 while ((key
= va_arg(ap
, char *))) {
633 value
= va_arg(ap
, char **);
636 if (strncmp(p
, key
, n
) != 0 ||
641 n
= strcspn(p
, separator
);
644 strchr(QUOTES
, p
[0]) &&
646 v
= strndup(p
+1, n
-2);
657 /* return empty value strings as NULL */
674 p
+= strcspn(p
, separator
);
682 char *truncate_nl(char *s
) {
685 s
[strcspn(s
, NEWLINE
)] = 0;
689 int get_process_name(pid_t pid
, char **name
) {
696 if (asprintf(&p
, "/proc/%lu/comm", (unsigned long) pid
) < 0)
699 r
= read_one_line_file(p
, name
);
709 int get_process_cmdline(pid_t pid
, size_t max_length
, char **line
) {
717 assert(max_length
> 0);
720 if (asprintf(&p
, "/proc/%lu/cmdline", (unsigned long) pid
) < 0)
729 if (!(r
= new(char, max_length
))) {
736 while ((c
= getc(f
)) != EOF
) {
758 size_t n
= MIN(left
-1, 3U);
766 /* Kernel threads have no argv[] */
773 if ((h
= get_process_name(pid
, &t
)) < 0)
776 h
= asprintf(&r
, "[%s]", t
);
787 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
795 return strndup(suffix
, b
);
805 if (!(r
= new(char, a
+b
+1)))
809 memcpy(r
+a
, suffix
, b
);
815 char *strappend(const char *s
, const char *suffix
) {
816 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
819 int readlink_malloc(const char *p
, char **r
) {
829 if (!(c
= new(char, l
)))
832 if ((n
= readlink(p
, c
, l
-1)) < 0) {
838 if ((size_t) n
< l
-1) {
849 int readlink_and_make_absolute(const char *p
, char **r
) {
856 if ((j
= readlink_malloc(p
, &target
)) < 0)
859 k
= file_in_same_dir(p
, target
);
869 int parent_of_path(const char *path
, char **_r
) {
870 const char *e
, *a
= NULL
, *b
= NULL
, *p
;
880 for (e
= path
; *e
; e
++) {
882 if (!slash
&& *e
== '/') {
886 } else if (slash
&& *e
!= '/')
901 r
= strndup(path
, p
-path
);
911 char *file_name_from_path(const char *p
) {
916 if ((r
= strrchr(p
, '/')))
922 bool path_is_absolute(const char *p
) {
928 bool is_path(const char *p
) {
930 return !!strchr(p
, '/');
933 char *path_make_absolute(const char *p
, const char *prefix
) {
938 /* Makes every item in the list an absolute path by prepending
939 * the prefix, if specified and necessary */
941 if (path_is_absolute(p
) || !prefix
)
944 if (asprintf(&r
, "%s/%s", prefix
, p
) < 0)
950 char *path_make_absolute_cwd(const char *p
) {
955 /* Similar to path_make_absolute(), but prefixes with the
956 * current working directory. */
958 if (path_is_absolute(p
))
961 if (!(cwd
= get_current_dir_name()))
964 r
= path_make_absolute(p
, cwd
);
970 char **strv_path_make_absolute_cwd(char **l
) {
973 /* Goes through every item in the string list and makes it
974 * absolute. This works in place and won't rollback any
975 * changes on failure. */
980 if (!(t
= path_make_absolute_cwd(*s
)))
990 char **strv_path_canonicalize(char **l
) {
998 /* Goes through every item in the string list and canonicalize
999 * the path. This works in place and won't rollback any
1000 * changes on failure. */
1002 STRV_FOREACH(s
, l
) {
1005 t
= path_make_absolute_cwd(*s
);
1014 u
= canonicalize_file_name(t
);
1018 if (errno
== ENOMEM
|| !errno
)
1035 int reset_all_signal_handlers(void) {
1038 for (sig
= 1; sig
< _NSIG
; sig
++) {
1039 struct sigaction sa
;
1041 if (sig
== SIGKILL
|| sig
== SIGSTOP
)
1045 sa
.sa_handler
= SIG_DFL
;
1046 sa
.sa_flags
= SA_RESTART
;
1048 /* On Linux the first two RT signals are reserved by
1049 * glibc, and sigaction() will return EINVAL for them. */
1050 if ((sigaction(sig
, &sa
, NULL
) < 0))
1051 if (errno
!= EINVAL
)
1058 char *strstrip(char *s
) {
1061 /* Drops trailing whitespace. Modifies the string in
1062 * place. Returns pointer to first non-space character */
1064 s
+= strspn(s
, WHITESPACE
);
1066 for (e
= s
; *e
; e
++)
1067 if (!strchr(WHITESPACE
, *e
))
1078 char *delete_chars(char *s
, const char *bad
) {
1081 /* Drops all whitespace, regardless where in the string */
1083 for (f
= s
, t
= s
; *f
; f
++) {
1084 if (strchr(bad
, *f
))
1095 char *file_in_same_dir(const char *path
, const char *filename
) {
1102 /* This removes the last component of path and appends
1103 * filename, unless the latter is absolute anyway or the
1106 if (path_is_absolute(filename
))
1107 return strdup(filename
);
1109 if (!(e
= strrchr(path
, '/')))
1110 return strdup(filename
);
1112 k
= strlen(filename
);
1113 if (!(r
= new(char, e
-path
+1+k
+1)))
1116 memcpy(r
, path
, e
-path
+1);
1117 memcpy(r
+(e
-path
)+1, filename
, k
+1);
1122 int safe_mkdir(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
1125 if (label_mkdir(path
, mode
) >= 0)
1126 if (chmod_and_chown(path
, mode
, uid
, gid
) < 0)
1129 if (lstat(path
, &st
) < 0)
1132 if ((st
.st_mode
& 0777) != mode
||
1135 !S_ISDIR(st
.st_mode
)) {
1144 int mkdir_parents(const char *path
, mode_t mode
) {
1149 /* Creates every parent directory in the path except the last
1152 p
= path
+ strspn(path
, "/");
1157 e
= p
+ strcspn(p
, "/");
1158 p
= e
+ strspn(e
, "/");
1160 /* Is this the last component? If so, then we're
1165 if (!(t
= strndup(path
, e
- path
)))
1168 r
= label_mkdir(t
, mode
);
1171 if (r
< 0 && errno
!= EEXIST
)
1176 int mkdir_p(const char *path
, mode_t mode
) {
1181 if ((r
= mkdir_parents(path
, mode
)) < 0)
1184 if (label_mkdir(path
, mode
) < 0 && errno
!= EEXIST
)
1190 int rmdir_parents(const char *path
, const char *stop
) {
1199 /* Skip trailing slashes */
1200 while (l
> 0 && path
[l
-1] == '/')
1206 /* Skip last component */
1207 while (l
> 0 && path
[l
-1] != '/')
1210 /* Skip trailing slashes */
1211 while (l
> 0 && path
[l
-1] == '/')
1217 if (!(t
= strndup(path
, l
)))
1220 if (path_startswith(stop
, t
)) {
1229 if (errno
!= ENOENT
)
1237 char hexchar(int x
) {
1238 static const char table
[16] = "0123456789abcdef";
1240 return table
[x
& 15];
1243 int unhexchar(char c
) {
1245 if (c
>= '0' && c
<= '9')
1248 if (c
>= 'a' && c
<= 'f')
1249 return c
- 'a' + 10;
1251 if (c
>= 'A' && c
<= 'F')
1252 return c
- 'A' + 10;
1257 char octchar(int x
) {
1258 return '0' + (x
& 7);
1261 int unoctchar(char c
) {
1263 if (c
>= '0' && c
<= '7')
1269 char decchar(int x
) {
1270 return '0' + (x
% 10);
1273 int undecchar(char c
) {
1275 if (c
>= '0' && c
<= '9')
1281 char *cescape(const char *s
) {
1287 /* Does C style string escaping. */
1289 if (!(r
= new(char, strlen(s
)*4 + 1)))
1292 for (f
= s
, t
= r
; *f
; f
++)
1338 /* For special chars we prefer octal over
1339 * hexadecimal encoding, simply because glib's
1340 * g_strescape() does the same */
1341 if ((*f
< ' ') || (*f
>= 127)) {
1343 *(t
++) = octchar((unsigned char) *f
>> 6);
1344 *(t
++) = octchar((unsigned char) *f
>> 3);
1345 *(t
++) = octchar((unsigned char) *f
);
1356 char *cunescape_length(const char *s
, size_t length
) {
1362 /* Undoes C style string escaping */
1364 if (!(r
= new(char, length
+1)))
1367 for (f
= s
, t
= r
; f
< s
+ length
; f
++) {
1410 /* This is an extension of the XDG syntax files */
1415 /* hexadecimal encoding */
1418 if ((a
= unhexchar(f
[1])) < 0 ||
1419 (b
= unhexchar(f
[2])) < 0) {
1420 /* Invalid escape code, let's take it literal then */
1424 *(t
++) = (char) ((a
<< 4) | b
);
1439 /* octal encoding */
1442 if ((a
= unoctchar(f
[0])) < 0 ||
1443 (b
= unoctchar(f
[1])) < 0 ||
1444 (c
= unoctchar(f
[2])) < 0) {
1445 /* Invalid escape code, let's take it literal then */
1449 *(t
++) = (char) ((a
<< 6) | (b
<< 3) | c
);
1457 /* premature end of string.*/
1462 /* Invalid escape code, let's take it literal then */
1474 char *cunescape(const char *s
) {
1475 return cunescape_length(s
, strlen(s
));
1478 char *xescape(const char *s
, const char *bad
) {
1482 /* Escapes all chars in bad, in addition to \ and all special
1483 * chars, in \xFF style escaping. May be reversed with
1486 if (!(r
= new(char, strlen(s
)*4+1)))
1489 for (f
= s
, t
= r
; *f
; f
++) {
1491 if ((*f
< ' ') || (*f
>= 127) ||
1492 (*f
== '\\') || strchr(bad
, *f
)) {
1495 *(t
++) = hexchar(*f
>> 4);
1496 *(t
++) = hexchar(*f
);
1506 char *bus_path_escape(const char *s
) {
1512 /* Escapes all chars that D-Bus' object path cannot deal
1513 * with. Can be reverse with bus_path_unescape() */
1515 if (!(r
= new(char, strlen(s
)*3+1)))
1518 for (f
= s
, t
= r
; *f
; f
++) {
1520 if (!(*f
>= 'A' && *f
<= 'Z') &&
1521 !(*f
>= 'a' && *f
<= 'z') &&
1522 !(*f
>= '0' && *f
<= '9')) {
1524 *(t
++) = hexchar(*f
>> 4);
1525 *(t
++) = hexchar(*f
);
1535 char *bus_path_unescape(const char *f
) {
1540 if (!(r
= strdup(f
)))
1543 for (t
= r
; *f
; f
++) {
1548 if ((a
= unhexchar(f
[1])) < 0 ||
1549 (b
= unhexchar(f
[2])) < 0) {
1550 /* Invalid escape code, let's take it literal then */
1553 *(t
++) = (char) ((a
<< 4) | b
);
1565 char *path_kill_slashes(char *path
) {
1569 /* Removes redundant inner and trailing slashes. Modifies the
1570 * passed string in-place.
1572 * ///foo///bar/ becomes /foo/bar
1575 for (f
= path
, t
= path
; *f
; f
++) {
1590 /* Special rule, if we are talking of the root directory, a
1591 trailing slash is good */
1593 if (t
== path
&& slash
)
1600 bool path_startswith(const char *path
, const char *prefix
) {
1604 if ((path
[0] == '/') != (prefix
[0] == '/'))
1610 path
+= strspn(path
, "/");
1611 prefix
+= strspn(prefix
, "/");
1619 a
= strcspn(path
, "/");
1620 b
= strcspn(prefix
, "/");
1625 if (memcmp(path
, prefix
, a
) != 0)
1633 bool path_equal(const char *a
, const char *b
) {
1637 if ((a
[0] == '/') != (b
[0] == '/'))
1643 a
+= strspn(a
, "/");
1644 b
+= strspn(b
, "/");
1646 if (*a
== 0 && *b
== 0)
1649 if (*a
== 0 || *b
== 0)
1652 j
= strcspn(a
, "/");
1653 k
= strcspn(b
, "/");
1658 if (memcmp(a
, b
, j
) != 0)
1666 char *ascii_strlower(char *t
) {
1671 for (p
= t
; *p
; p
++)
1672 if (*p
>= 'A' && *p
<= 'Z')
1673 *p
= *p
- 'A' + 'a';
1678 bool ignore_file(const char *filename
) {
1682 filename
[0] == '.' ||
1683 streq(filename
, "lost+found") ||
1684 endswith(filename
, "~") ||
1685 endswith(filename
, ".rpmnew") ||
1686 endswith(filename
, ".rpmsave") ||
1687 endswith(filename
, ".rpmorig") ||
1688 endswith(filename
, ".dpkg-old") ||
1689 endswith(filename
, ".dpkg-new") ||
1690 endswith(filename
, ".swp");
1693 int fd_nonblock(int fd
, bool nonblock
) {
1698 if ((flags
= fcntl(fd
, F_GETFL
, 0)) < 0)
1702 flags
|= O_NONBLOCK
;
1704 flags
&= ~O_NONBLOCK
;
1706 if (fcntl(fd
, F_SETFL
, flags
) < 0)
1712 int fd_cloexec(int fd
, bool cloexec
) {
1717 if ((flags
= fcntl(fd
, F_GETFD
, 0)) < 0)
1721 flags
|= FD_CLOEXEC
;
1723 flags
&= ~FD_CLOEXEC
;
1725 if (fcntl(fd
, F_SETFD
, flags
) < 0)
1731 int close_all_fds(const int except
[], unsigned n_except
) {
1736 if (!(d
= opendir("/proc/self/fd")))
1739 while ((de
= readdir(d
))) {
1742 if (ignore_file(de
->d_name
))
1745 if ((r
= safe_atoi(de
->d_name
, &fd
)) < 0)
1759 for (i
= 0; i
< n_except
; i
++)
1760 if (except
[i
] == fd
) {
1769 if ((r
= close_nointr(fd
)) < 0) {
1770 /* Valgrind has its own FD and doesn't want to have it closed */
1783 bool chars_intersect(const char *a
, const char *b
) {
1786 /* Returns true if any of the chars in a are in b. */
1787 for (p
= a
; *p
; p
++)
1794 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
1804 sec
= (time_t) (t
/ USEC_PER_SEC
);
1806 if (strftime(buf
, l
, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec
, &tm
)) <= 0)
1812 char *format_timestamp_pretty(char *buf
, size_t l
, usec_t t
) {
1815 n
= now(CLOCK_REALTIME
);
1817 if (t
<= 0 || t
> n
|| t
+ USEC_PER_DAY
*7 <= t
)
1822 if (d
>= USEC_PER_YEAR
)
1823 snprintf(buf
, l
, "%llu years and %llu months ago",
1824 (unsigned long long) (d
/ USEC_PER_YEAR
),
1825 (unsigned long long) ((d
% USEC_PER_YEAR
) / USEC_PER_MONTH
));
1826 else if (d
>= USEC_PER_MONTH
)
1827 snprintf(buf
, l
, "%llu months and %llu days ago",
1828 (unsigned long long) (d
/ USEC_PER_MONTH
),
1829 (unsigned long long) ((d
% USEC_PER_MONTH
) / USEC_PER_DAY
));
1830 else if (d
>= USEC_PER_WEEK
)
1831 snprintf(buf
, l
, "%llu weeks and %llu days ago",
1832 (unsigned long long) (d
/ USEC_PER_WEEK
),
1833 (unsigned long long) ((d
% USEC_PER_WEEK
) / USEC_PER_DAY
));
1834 else if (d
>= 2*USEC_PER_DAY
)
1835 snprintf(buf
, l
, "%llu days ago", (unsigned long long) (d
/ USEC_PER_DAY
));
1836 else if (d
>= 25*USEC_PER_HOUR
)
1837 snprintf(buf
, l
, "1 day and %lluh ago",
1838 (unsigned long long) ((d
- USEC_PER_DAY
) / USEC_PER_HOUR
));
1839 else if (d
>= 6*USEC_PER_HOUR
)
1840 snprintf(buf
, l
, "%lluh ago",
1841 (unsigned long long) (d
/ USEC_PER_HOUR
));
1842 else if (d
>= USEC_PER_HOUR
)
1843 snprintf(buf
, l
, "%lluh %llumin ago",
1844 (unsigned long long) (d
/ USEC_PER_HOUR
),
1845 (unsigned long long) ((d
% USEC_PER_HOUR
) / USEC_PER_MINUTE
));
1846 else if (d
>= 5*USEC_PER_MINUTE
)
1847 snprintf(buf
, l
, "%llumin ago",
1848 (unsigned long long) (d
/ USEC_PER_MINUTE
));
1849 else if (d
>= USEC_PER_MINUTE
)
1850 snprintf(buf
, l
, "%llumin %llus ago",
1851 (unsigned long long) (d
/ USEC_PER_MINUTE
),
1852 (unsigned long long) ((d
% USEC_PER_MINUTE
) / USEC_PER_SEC
));
1853 else if (d
>= USEC_PER_SEC
)
1854 snprintf(buf
, l
, "%llus ago",
1855 (unsigned long long) (d
/ USEC_PER_SEC
));
1856 else if (d
>= USEC_PER_MSEC
)
1857 snprintf(buf
, l
, "%llums ago",
1858 (unsigned long long) (d
/ USEC_PER_MSEC
));
1860 snprintf(buf
, l
, "%lluus ago",
1861 (unsigned long long) d
);
1863 snprintf(buf
, l
, "now");
1869 char *format_timespan(char *buf
, size_t l
, usec_t t
) {
1870 static const struct {
1874 { "w", USEC_PER_WEEK
},
1875 { "d", USEC_PER_DAY
},
1876 { "h", USEC_PER_HOUR
},
1877 { "min", USEC_PER_MINUTE
},
1878 { "s", USEC_PER_SEC
},
1879 { "ms", USEC_PER_MSEC
},
1889 if (t
== (usec_t
) -1)
1893 snprintf(p
, l
, "0");
1898 /* The result of this function can be parsed with parse_usec */
1900 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
1904 if (t
< table
[i
].usec
)
1910 k
= snprintf(p
, l
, "%s%llu%s", p
> buf
? " " : "", (unsigned long long) (t
/ table
[i
].usec
), table
[i
].suffix
);
1911 n
= MIN((size_t) k
, l
);
1924 bool fstype_is_network(const char *fstype
) {
1925 static const char * const table
[] = {
1937 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
1938 if (streq(table
[i
], fstype
))
1947 if ((fd
= open("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
)) < 0)
1952 TIOCL_GETKMSGREDIRECT
,
1956 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0)
1959 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
1962 if (ioctl(fd
, VT_ACTIVATE
, vt
) < 0)
1965 close_nointr_nofail(r
);
1969 int read_one_char(FILE *f
, char *ret
, bool *need_nl
) {
1970 struct termios old_termios
, new_termios
;
1977 if (tcgetattr(fileno(f
), &old_termios
) >= 0) {
1978 new_termios
= old_termios
;
1980 new_termios
.c_lflag
&= ~ICANON
;
1981 new_termios
.c_cc
[VMIN
] = 1;
1982 new_termios
.c_cc
[VTIME
] = 0;
1984 if (tcsetattr(fileno(f
), TCSADRAIN
, &new_termios
) >= 0) {
1987 k
= fread(&c
, 1, 1, f
);
1989 tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
1995 *need_nl
= c
!= '\n';
2002 if (!(fgets(line
, sizeof(line
), f
)))
2007 if (strlen(line
) != 1)
2017 int ask(char *ret
, const char *replies
, const char *text
, ...) {
2024 on_tty
= isatty(STDOUT_FILENO
);
2030 bool need_nl
= true;
2033 fputs("\x1B[1m", stdout
);
2040 fputs("\x1B[0m", stdout
);
2044 if ((r
= read_one_char(stdin
, &c
, &need_nl
)) < 0) {
2046 if (r
== -EBADMSG
) {
2047 puts("Bad input, please try again.");
2058 if (strchr(replies
, c
)) {
2063 puts("Read unexpected character, please try again.");
2067 int reset_terminal(int fd
) {
2068 struct termios termios
;
2072 /* Set terminal to some sane defaults */
2076 /* We leave locked terminal attributes untouched, so that
2077 * Plymouth may set whatever it wants to set, and we don't
2078 * interfere with that. */
2080 /* Disable exclusive mode, just in case */
2081 ioctl(fd
, TIOCNXCL
);
2083 /* Enable console unicode mode */
2085 ioctl(fd
, KDSKBMODE
, &arg
);
2087 if (tcgetattr(fd
, &termios
) < 0) {
2092 /* We only reset the stuff that matters to the software. How
2093 * hardware is set up we don't touch assuming that somebody
2094 * else will do that for us */
2096 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
2097 termios
.c_iflag
|= ICRNL
| IMAXBEL
| IUTF8
;
2098 termios
.c_oflag
|= ONLCR
;
2099 termios
.c_cflag
|= CREAD
;
2100 termios
.c_lflag
= ISIG
| ICANON
| IEXTEN
| ECHO
| ECHOE
| ECHOK
| ECHOCTL
| ECHOPRT
| ECHOKE
;
2102 termios
.c_cc
[VINTR
] = 03; /* ^C */
2103 termios
.c_cc
[VQUIT
] = 034; /* ^\ */
2104 termios
.c_cc
[VERASE
] = 0177;
2105 termios
.c_cc
[VKILL
] = 025; /* ^X */
2106 termios
.c_cc
[VEOF
] = 04; /* ^D */
2107 termios
.c_cc
[VSTART
] = 021; /* ^Q */
2108 termios
.c_cc
[VSTOP
] = 023; /* ^S */
2109 termios
.c_cc
[VSUSP
] = 032; /* ^Z */
2110 termios
.c_cc
[VLNEXT
] = 026; /* ^V */
2111 termios
.c_cc
[VWERASE
] = 027; /* ^W */
2112 termios
.c_cc
[VREPRINT
] = 022; /* ^R */
2113 termios
.c_cc
[VEOL
] = 0;
2114 termios
.c_cc
[VEOL2
] = 0;
2116 termios
.c_cc
[VTIME
] = 0;
2117 termios
.c_cc
[VMIN
] = 1;
2119 if (tcsetattr(fd
, TCSANOW
, &termios
) < 0)
2123 /* Just in case, flush all crap out */
2124 tcflush(fd
, TCIOFLUSH
);
2129 int open_terminal(const char *name
, int mode
) {
2132 if ((fd
= open(name
, mode
)) < 0)
2135 if ((r
= isatty(fd
)) < 0) {
2136 close_nointr_nofail(fd
);
2141 close_nointr_nofail(fd
);
2148 int flush_fd(int fd
) {
2149 struct pollfd pollfd
;
2153 pollfd
.events
= POLLIN
;
2160 if ((r
= poll(&pollfd
, 1, 0)) < 0) {
2171 if ((l
= read(fd
, buf
, sizeof(buf
))) < 0) {
2176 if (errno
== EAGAIN
)
2187 int acquire_terminal(const char *name
, bool fail
, bool force
, bool ignore_tiocstty_eperm
) {
2188 int fd
= -1, notify
= -1, r
, wd
= -1;
2192 /* We use inotify to be notified when the tty is closed. We
2193 * create the watch before checking if we can actually acquire
2194 * it, so that we don't lose any event.
2196 * Note: strictly speaking this actually watches for the
2197 * device being closed, it does *not* really watch whether a
2198 * tty loses its controlling process. However, unless some
2199 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2200 * its tty otherwise this will not become a problem. As long
2201 * as the administrator makes sure not configure any service
2202 * on the same tty as an untrusted user this should not be a
2203 * problem. (Which he probably should not do anyway.) */
2205 if (!fail
&& !force
) {
2206 if ((notify
= inotify_init1(IN_CLOEXEC
)) < 0) {
2211 if ((wd
= inotify_add_watch(notify
, name
, IN_CLOSE
)) < 0) {
2219 if ((r
= flush_fd(notify
)) < 0)
2222 /* We pass here O_NOCTTY only so that we can check the return
2223 * value TIOCSCTTY and have a reliable way to figure out if we
2224 * successfully became the controlling process of the tty */
2225 if ((fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
)) < 0)
2228 /* First, try to get the tty */
2229 r
= ioctl(fd
, TIOCSCTTY
, force
);
2231 /* Sometimes it makes sense to ignore TIOCSCTTY
2232 * returning EPERM, i.e. when very likely we already
2233 * are have this controlling terminal. */
2234 if (r
< 0 && errno
== EPERM
&& ignore_tiocstty_eperm
)
2237 if (r
< 0 && (force
|| fail
|| errno
!= EPERM
)) {
2247 assert(notify
>= 0);
2250 struct inotify_event e
;
2253 if ((l
= read(notify
, &e
, sizeof(e
))) != sizeof(e
)) {
2267 if (e
.wd
!= wd
|| !(e
.mask
& IN_CLOSE
)) {
2275 /* We close the tty fd here since if the old session
2276 * ended our handle will be dead. It's important that
2277 * we do this after sleeping, so that we don't enter
2278 * an endless loop. */
2279 close_nointr_nofail(fd
);
2283 close_nointr_nofail(notify
);
2285 if ((r
= reset_terminal(fd
)) < 0)
2286 log_warning("Failed to reset terminal: %s", strerror(-r
));
2292 close_nointr_nofail(fd
);
2295 close_nointr_nofail(notify
);
2300 int release_terminal(void) {
2302 struct sigaction sa_old
, sa_new
;
2304 if ((fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_NDELAY
)) < 0)
2307 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2308 * by our own TIOCNOTTY */
2311 sa_new
.sa_handler
= SIG_IGN
;
2312 sa_new
.sa_flags
= SA_RESTART
;
2313 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
2315 if (ioctl(fd
, TIOCNOTTY
) < 0)
2318 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
2320 close_nointr_nofail(fd
);
2324 int sigaction_many(const struct sigaction
*sa
, ...) {
2329 while ((sig
= va_arg(ap
, int)) > 0)
2330 if (sigaction(sig
, sa
, NULL
) < 0)
2337 int ignore_signals(int sig
, ...) {
2338 struct sigaction sa
;
2343 sa
.sa_handler
= SIG_IGN
;
2344 sa
.sa_flags
= SA_RESTART
;
2346 if (sigaction(sig
, &sa
, NULL
) < 0)
2350 while ((sig
= va_arg(ap
, int)) > 0)
2351 if (sigaction(sig
, &sa
, NULL
) < 0)
2358 int default_signals(int sig
, ...) {
2359 struct sigaction sa
;
2364 sa
.sa_handler
= SIG_DFL
;
2365 sa
.sa_flags
= SA_RESTART
;
2367 if (sigaction(sig
, &sa
, NULL
) < 0)
2371 while ((sig
= va_arg(ap
, int)) > 0)
2372 if (sigaction(sig
, &sa
, NULL
) < 0)
2379 int close_pipe(int p
[]) {
2385 a
= close_nointr(p
[0]);
2390 b
= close_nointr(p
[1]);
2394 return a
< 0 ? a
: b
;
2397 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2406 while (nbytes
> 0) {
2409 if ((k
= read(fd
, p
, nbytes
)) <= 0) {
2411 if (k
< 0 && errno
== EINTR
)
2414 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2415 struct pollfd pollfd
;
2419 pollfd
.events
= POLLIN
;
2421 if (poll(&pollfd
, 1, -1) < 0) {
2425 return n
> 0 ? n
: -errno
;
2428 if (pollfd
.revents
!= POLLIN
)
2429 return n
> 0 ? n
: -EIO
;
2434 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2445 ssize_t
loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2454 while (nbytes
> 0) {
2457 if ((k
= write(fd
, p
, nbytes
)) <= 0) {
2459 if (k
< 0 && errno
== EINTR
)
2462 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2463 struct pollfd pollfd
;
2467 pollfd
.events
= POLLOUT
;
2469 if (poll(&pollfd
, 1, -1) < 0) {
2473 return n
> 0 ? n
: -errno
;
2476 if (pollfd
.revents
!= POLLOUT
)
2477 return n
> 0 ? n
: -EIO
;
2482 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2493 int path_is_mount_point(const char *t
) {
2498 if (lstat(t
, &a
) < 0) {
2499 if (errno
== ENOENT
)
2505 if ((r
= parent_of_path(t
, &parent
)) < 0)
2508 r
= lstat(parent
, &b
);
2514 return a
.st_dev
!= b
.st_dev
;
2517 int parse_usec(const char *t
, usec_t
*usec
) {
2518 static const struct {
2522 { "sec", USEC_PER_SEC
},
2523 { "s", USEC_PER_SEC
},
2524 { "min", USEC_PER_MINUTE
},
2525 { "hr", USEC_PER_HOUR
},
2526 { "h", USEC_PER_HOUR
},
2527 { "d", USEC_PER_DAY
},
2528 { "w", USEC_PER_WEEK
},
2529 { "msec", USEC_PER_MSEC
},
2530 { "ms", USEC_PER_MSEC
},
2531 { "m", USEC_PER_MINUTE
},
2534 { "", USEC_PER_SEC
},
2550 l
= strtoll(p
, &e
, 10);
2561 e
+= strspn(e
, WHITESPACE
);
2563 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
2564 if (startswith(e
, table
[i
].suffix
)) {
2565 r
+= (usec_t
) l
* table
[i
].usec
;
2566 p
= e
+ strlen(table
[i
].suffix
);
2570 if (i
>= ELEMENTSOF(table
))
2580 int make_stdio(int fd
) {
2585 r
= dup2(fd
, STDIN_FILENO
);
2586 s
= dup2(fd
, STDOUT_FILENO
);
2587 t
= dup2(fd
, STDERR_FILENO
);
2590 close_nointr_nofail(fd
);
2592 if (r
< 0 || s
< 0 || t
< 0)
2598 bool is_clean_exit(int code
, int status
) {
2600 if (code
== CLD_EXITED
)
2603 /* If a daemon does not implement handlers for some of the
2604 * signals that's not considered an unclean shutdown */
2605 if (code
== CLD_KILLED
)
2609 status
== SIGTERM
||
2615 bool is_clean_exit_lsb(int code
, int status
) {
2617 if (is_clean_exit(code
, status
))
2621 code
== CLD_EXITED
&&
2622 (status
== EXIT_NOTINSTALLED
|| status
== EXIT_NOTCONFIGURED
);
2625 bool is_device_path(const char *path
) {
2627 /* Returns true on paths that refer to a device, either in
2628 * sysfs or in /dev */
2631 path_startswith(path
, "/dev/") ||
2632 path_startswith(path
, "/sys/");
2635 int dir_is_empty(const char *path
) {
2638 struct dirent buf
, *de
;
2640 if (!(d
= opendir(path
)))
2644 if ((r
= readdir_r(d
, &buf
, &de
)) > 0) {
2654 if (!ignore_file(de
->d_name
)) {
2664 unsigned long long random_ull(void) {
2669 if ((fd
= open("/dev/urandom", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
)) < 0)
2672 r
= loop_read(fd
, &ull
, sizeof(ull
), true);
2673 close_nointr_nofail(fd
);
2675 if (r
!= sizeof(ull
))
2681 return random() * RAND_MAX
+ random();
2684 void rename_process(const char name
[8]) {
2687 prctl(PR_SET_NAME
, name
);
2689 /* This is a like a poor man's setproctitle(). The string
2690 * passed should fit in 7 chars (i.e. the length of
2693 if (program_invocation_name
)
2694 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2697 void sigset_add_many(sigset_t
*ss
, ...) {
2704 while ((sig
= va_arg(ap
, int)) > 0)
2705 assert_se(sigaddset(ss
, sig
) == 0);
2709 char* gethostname_malloc(void) {
2712 assert_se(uname(&u
) >= 0);
2715 return strdup(u
.nodename
);
2717 return strdup(u
.sysname
);
2720 char* getlogname_malloc(void) {
2724 struct passwd pwbuf
, *pw
= NULL
;
2727 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2732 /* Shortcut things to avoid NSS lookups */
2734 return strdup("root");
2736 if ((bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
)) <= 0)
2739 if (!(buf
= malloc(bufsize
)))
2742 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
) {
2743 name
= strdup(pw
->pw_name
);
2750 if (asprintf(&name
, "%lu", (unsigned long) uid
) < 0)
2756 int getttyname_malloc(char **r
) {
2757 char path
[PATH_MAX
], *p
, *c
;
2762 if ((k
= ttyname_r(STDIN_FILENO
, path
, sizeof(path
))) != 0)
2768 if (startswith(path
, "/dev/"))
2771 if (!(c
= strdup(p
)))
2778 static int rm_rf_children(int fd
, bool only_dirs
) {
2784 /* This returns the first error we run into, but nevertheless
2787 if (!(d
= fdopendir(fd
))) {
2788 close_nointr_nofail(fd
);
2790 return errno
== ENOENT
? 0 : -errno
;
2794 struct dirent buf
, *de
;
2798 if ((r
= readdir_r(d
, &buf
, &de
)) != 0) {
2807 if (streq(de
->d_name
, ".") || streq(de
->d_name
, ".."))
2810 if (de
->d_type
== DT_UNKNOWN
) {
2813 if (fstatat(fd
, de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0) {
2814 if (ret
== 0 && errno
!= ENOENT
)
2819 is_dir
= S_ISDIR(st
.st_mode
);
2821 is_dir
= de
->d_type
== DT_DIR
;
2826 if ((subdir_fd
= openat(fd
, de
->d_name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
)) < 0) {
2827 if (ret
== 0 && errno
!= ENOENT
)
2832 if ((r
= rm_rf_children(subdir_fd
, only_dirs
)) < 0) {
2837 if (unlinkat(fd
, de
->d_name
, AT_REMOVEDIR
) < 0) {
2838 if (ret
== 0 && errno
!= ENOENT
)
2841 } else if (!only_dirs
) {
2843 if (unlinkat(fd
, de
->d_name
, 0) < 0) {
2844 if (ret
== 0 && errno
!= ENOENT
)
2855 int rm_rf(const char *path
, bool only_dirs
, bool delete_root
) {
2861 if ((fd
= open(path
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
)) < 0) {
2863 if (errno
!= ENOTDIR
)
2866 if (delete_root
&& !only_dirs
)
2867 if (unlink(path
) < 0)
2873 r
= rm_rf_children(fd
, only_dirs
);
2876 if (rmdir(path
) < 0) {
2884 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2887 /* Under the assumption that we are running privileged we
2888 * first change the access mode and only then hand out
2889 * ownership to avoid a window where access is too open. */
2891 if (chmod(path
, mode
) < 0)
2894 if (chown(path
, uid
, gid
) < 0)
2900 cpu_set_t
* cpu_set_malloc(unsigned *ncpus
) {
2904 /* Allocates the cpuset in the right size */
2907 if (!(r
= CPU_ALLOC(n
)))
2910 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), r
) >= 0) {
2911 CPU_ZERO_S(CPU_ALLOC_SIZE(n
), r
);
2921 if (errno
!= EINVAL
)
2928 void status_vprintf(const char *format
, va_list ap
) {
2934 /* This independent of logging, as status messages are
2935 * optional and go exclusively to the console. */
2937 if (vasprintf(&s
, format
, ap
) < 0)
2940 if ((fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
)) < 0)
2943 write(fd
, s
, strlen(s
));
2949 close_nointr_nofail(fd
);
2952 void status_printf(const char *format
, ...) {
2957 va_start(ap
, format
);
2958 status_vprintf(format
, ap
);
2962 void status_welcome(void) {
2964 #if defined(TARGET_FEDORA)
2967 if (read_one_line_file("/etc/system-release", &r
) < 0)
2972 /* This tries to mimic the color magic the old Red Hat sysinit
2975 if (startswith(r
, "Red Hat"))
2976 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r
); /* Red for RHEL */
2977 else if (startswith(r
, "Fedora"))
2978 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r
); /* Blue for Fedora */
2980 status_printf("Welcome to %s!\n", r
);
2984 #elif defined(TARGET_SUSE)
2987 if (read_one_line_file("/etc/SuSE-release", &r
) < 0)
2992 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r
); /* Green for SUSE */
2995 #elif defined(TARGET_GENTOO)
2998 if (read_one_line_file("/etc/gentoo-release", &r
) < 0)
3003 status_printf("Welcome to \x1B[1;34m%s\x1B[0m!\n", r
); /* Light Blue for Gentoo */
3007 #elif defined(TARGET_DEBIAN)
3010 if (read_one_line_file("/etc/debian_version", &r
) < 0)
3015 status_printf("Welcome to Debian \x1B[1;31m%s\x1B[0m!\n", r
); /* Light Red for Debian */
3018 #elif defined(TARGET_ARCH)
3019 status_printf("Welcome to \x1B[1;36mArch Linux\x1B[0m!\n"); /* Cyan for Arch */
3021 #warning "You probably should add a welcome text logic here."
3025 char *replace_env(const char *format
, char **env
) {
3032 const char *e
, *word
= format
;
3037 for (e
= format
; *e
; e
++) {
3048 if (!(k
= strnappend(r
, word
, e
-word
-1)))
3057 } else if (*e
== '$') {
3058 if (!(k
= strnappend(r
, word
, e
-word
)))
3074 if (!(t
= strv_env_get_with_length(env
, word
+2, e
-word
-2)))
3077 if (!(k
= strappend(r
, t
)))
3090 if (!(k
= strnappend(r
, word
, e
-word
)))
3101 char **replace_env_argv(char **argv
, char **env
) {
3103 unsigned k
= 0, l
= 0;
3105 l
= strv_length(argv
);
3107 if (!(r
= new(char*, l
+1)))
3110 STRV_FOREACH(i
, argv
) {
3112 /* If $FOO appears as single word, replace it by the split up variable */
3113 if ((*i
)[0] == '$' && (*i
)[1] != '{') {
3118 if ((e
= strv_env_get(env
, *i
+1))) {
3120 if (!(m
= strv_split_quoted(e
))) {
3131 if (!(w
= realloc(r
, sizeof(char*) * (l
+1)))) {
3140 memcpy(r
+ k
, m
, q
* sizeof(char*));
3148 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3149 if (!(r
[k
++] = replace_env(*i
, env
))) {
3160 static __thread
int parsed_columns
= 0;
3163 if (parsed_columns
> 0)
3164 return parsed_columns
;
3166 if ((e
= getenv("COLUMNS")))
3167 parsed_columns
= atoi(e
);
3169 if (parsed_columns
<= 0) {
3173 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &ws
) >= 0)
3174 parsed_columns
= ws
.ws_col
;
3177 if (parsed_columns
<= 0)
3178 parsed_columns
= 80;
3180 return parsed_columns
;
3183 int running_in_chroot(void) {
3189 /* Only works as root */
3191 if (stat("/proc/1/root", &a
) < 0)
3194 if (stat("/", &b
) < 0)
3198 a
.st_dev
!= b
.st_dev
||
3199 a
.st_ino
!= b
.st_ino
;
3202 char *ellipsize(const char *s
, unsigned length
, unsigned percent
) {
3207 assert(percent
<= 100);
3208 assert(length
>= 3);
3212 if (l
<= 3 || l
<= length
)
3215 if (!(r
= new0(char, length
+1)))
3218 x
= (length
* percent
) / 100;
3228 s
+ l
- (length
- x
- 3),
3234 int touch(const char *path
) {
3239 if ((fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, 0666)) < 0)
3242 close_nointr_nofail(fd
);
3246 char *unquote(const char *s
, const char* quotes
) {
3250 if ((l
= strlen(s
)) < 2)
3253 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
3254 return strndup(s
+1, l
-2);
3259 int wait_for_terminate(pid_t pid
, siginfo_t
*status
) {
3266 if (waitid(P_PID
, pid
, status
, WEXITED
) < 0) {
3278 int wait_for_terminate_and_warn(const char *name
, pid_t pid
) {
3285 if ((r
= wait_for_terminate(pid
, &status
)) < 0) {
3286 log_warning("Failed to wait for %s: %s", name
, strerror(-r
));
3290 if (status
.si_code
== CLD_EXITED
) {
3291 if (status
.si_status
!= 0) {
3292 log_warning("%s failed with error code %i.", name
, status
.si_status
);
3296 log_debug("%s succeeded.", name
);
3299 } else if (status
.si_code
== CLD_KILLED
||
3300 status
.si_code
== CLD_DUMPED
) {
3302 log_warning("%s terminated by signal %s.", name
, signal_to_string(status
.si_status
));
3306 log_warning("%s failed due to unknown reason.", name
);
3311 static const char *const ioprio_class_table
[] = {
3312 [IOPRIO_CLASS_NONE
] = "none",
3313 [IOPRIO_CLASS_RT
] = "realtime",
3314 [IOPRIO_CLASS_BE
] = "best-effort",
3315 [IOPRIO_CLASS_IDLE
] = "idle"
3318 DEFINE_STRING_TABLE_LOOKUP(ioprio_class
, int);
3320 static const char *const sigchld_code_table
[] = {
3321 [CLD_EXITED
] = "exited",
3322 [CLD_KILLED
] = "killed",
3323 [CLD_DUMPED
] = "dumped",
3324 [CLD_TRAPPED
] = "trapped",
3325 [CLD_STOPPED
] = "stopped",
3326 [CLD_CONTINUED
] = "continued",
3329 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
3331 static const char *const log_facility_table
[LOG_NFACILITIES
] = {
3332 [LOG_FAC(LOG_KERN
)] = "kern",
3333 [LOG_FAC(LOG_USER
)] = "user",
3334 [LOG_FAC(LOG_MAIL
)] = "mail",
3335 [LOG_FAC(LOG_DAEMON
)] = "daemon",
3336 [LOG_FAC(LOG_AUTH
)] = "auth",
3337 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
3338 [LOG_FAC(LOG_LPR
)] = "lpr",
3339 [LOG_FAC(LOG_NEWS
)] = "news",
3340 [LOG_FAC(LOG_UUCP
)] = "uucp",
3341 [LOG_FAC(LOG_CRON
)] = "cron",
3342 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
3343 [LOG_FAC(LOG_FTP
)] = "ftp",
3344 [LOG_FAC(LOG_LOCAL0
)] = "local0",
3345 [LOG_FAC(LOG_LOCAL1
)] = "local1",
3346 [LOG_FAC(LOG_LOCAL2
)] = "local2",
3347 [LOG_FAC(LOG_LOCAL3
)] = "local3",
3348 [LOG_FAC(LOG_LOCAL4
)] = "local4",
3349 [LOG_FAC(LOG_LOCAL5
)] = "local5",
3350 [LOG_FAC(LOG_LOCAL6
)] = "local6",
3351 [LOG_FAC(LOG_LOCAL7
)] = "local7"
3354 DEFINE_STRING_TABLE_LOOKUP(log_facility
, int);
3356 static const char *const log_level_table
[] = {
3357 [LOG_EMERG
] = "emerg",
3358 [LOG_ALERT
] = "alert",
3359 [LOG_CRIT
] = "crit",
3361 [LOG_WARNING
] = "warning",
3362 [LOG_NOTICE
] = "notice",
3363 [LOG_INFO
] = "info",
3364 [LOG_DEBUG
] = "debug"
3367 DEFINE_STRING_TABLE_LOOKUP(log_level
, int);
3369 static const char* const sched_policy_table
[] = {
3370 [SCHED_OTHER
] = "other",
3371 [SCHED_BATCH
] = "batch",
3372 [SCHED_IDLE
] = "idle",
3373 [SCHED_FIFO
] = "fifo",
3377 DEFINE_STRING_TABLE_LOOKUP(sched_policy
, int);
3379 static const char* const rlimit_table
[] = {
3380 [RLIMIT_CPU
] = "LimitCPU",
3381 [RLIMIT_FSIZE
] = "LimitFSIZE",
3382 [RLIMIT_DATA
] = "LimitDATA",
3383 [RLIMIT_STACK
] = "LimitSTACK",
3384 [RLIMIT_CORE
] = "LimitCORE",
3385 [RLIMIT_RSS
] = "LimitRSS",
3386 [RLIMIT_NOFILE
] = "LimitNOFILE",
3387 [RLIMIT_AS
] = "LimitAS",
3388 [RLIMIT_NPROC
] = "LimitNPROC",
3389 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
3390 [RLIMIT_LOCKS
] = "LimitLOCKS",
3391 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
3392 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
3393 [RLIMIT_NICE
] = "LimitNICE",
3394 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
3395 [RLIMIT_RTTIME
] = "LimitRTTIME"
3398 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
3400 static const char* const ip_tos_table
[] = {
3401 [IPTOS_LOWDELAY
] = "low-delay",
3402 [IPTOS_THROUGHPUT
] = "throughput",
3403 [IPTOS_RELIABILITY
] = "reliability",
3404 [IPTOS_LOWCOST
] = "low-cost",
3407 DEFINE_STRING_TABLE_LOOKUP(ip_tos
, int);
3409 static const char *const signal_table
[] = {
3426 [SIGSTKFLT
] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3437 [SIGVTALRM
] = "VTALRM",
3439 [SIGWINCH
] = "WINCH",
3445 DEFINE_STRING_TABLE_LOOKUP(signal
, int);