]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/util.c
f41861b64eda1db93d0a50cb7cfb710f206027db
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 streq(filename
, "aquota.user") ||
1685 streq(filename
, "aquota.group") ||
1686 endswith(filename
, "~") ||
1687 endswith(filename
, ".rpmnew") ||
1688 endswith(filename
, ".rpmsave") ||
1689 endswith(filename
, ".rpmorig") ||
1690 endswith(filename
, ".dpkg-old") ||
1691 endswith(filename
, ".dpkg-new") ||
1692 endswith(filename
, ".swp");
1695 int fd_nonblock(int fd
, bool nonblock
) {
1700 if ((flags
= fcntl(fd
, F_GETFL
, 0)) < 0)
1704 flags
|= O_NONBLOCK
;
1706 flags
&= ~O_NONBLOCK
;
1708 if (fcntl(fd
, F_SETFL
, flags
) < 0)
1714 int fd_cloexec(int fd
, bool cloexec
) {
1719 if ((flags
= fcntl(fd
, F_GETFD
, 0)) < 0)
1723 flags
|= FD_CLOEXEC
;
1725 flags
&= ~FD_CLOEXEC
;
1727 if (fcntl(fd
, F_SETFD
, flags
) < 0)
1733 int close_all_fds(const int except
[], unsigned n_except
) {
1738 if (!(d
= opendir("/proc/self/fd")))
1741 while ((de
= readdir(d
))) {
1744 if (ignore_file(de
->d_name
))
1747 if ((r
= safe_atoi(de
->d_name
, &fd
)) < 0)
1761 for (i
= 0; i
< n_except
; i
++)
1762 if (except
[i
] == fd
) {
1771 if ((r
= close_nointr(fd
)) < 0) {
1772 /* Valgrind has its own FD and doesn't want to have it closed */
1785 bool chars_intersect(const char *a
, const char *b
) {
1788 /* Returns true if any of the chars in a are in b. */
1789 for (p
= a
; *p
; p
++)
1796 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
1806 sec
= (time_t) (t
/ USEC_PER_SEC
);
1808 if (strftime(buf
, l
, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec
, &tm
)) <= 0)
1814 char *format_timestamp_pretty(char *buf
, size_t l
, usec_t t
) {
1817 n
= now(CLOCK_REALTIME
);
1819 if (t
<= 0 || t
> n
|| t
+ USEC_PER_DAY
*7 <= t
)
1824 if (d
>= USEC_PER_YEAR
)
1825 snprintf(buf
, l
, "%llu years and %llu months ago",
1826 (unsigned long long) (d
/ USEC_PER_YEAR
),
1827 (unsigned long long) ((d
% USEC_PER_YEAR
) / USEC_PER_MONTH
));
1828 else if (d
>= USEC_PER_MONTH
)
1829 snprintf(buf
, l
, "%llu months and %llu days ago",
1830 (unsigned long long) (d
/ USEC_PER_MONTH
),
1831 (unsigned long long) ((d
% USEC_PER_MONTH
) / USEC_PER_DAY
));
1832 else if (d
>= USEC_PER_WEEK
)
1833 snprintf(buf
, l
, "%llu weeks and %llu days ago",
1834 (unsigned long long) (d
/ USEC_PER_WEEK
),
1835 (unsigned long long) ((d
% USEC_PER_WEEK
) / USEC_PER_DAY
));
1836 else if (d
>= 2*USEC_PER_DAY
)
1837 snprintf(buf
, l
, "%llu days ago", (unsigned long long) (d
/ USEC_PER_DAY
));
1838 else if (d
>= 25*USEC_PER_HOUR
)
1839 snprintf(buf
, l
, "1 day and %lluh ago",
1840 (unsigned long long) ((d
- USEC_PER_DAY
) / USEC_PER_HOUR
));
1841 else if (d
>= 6*USEC_PER_HOUR
)
1842 snprintf(buf
, l
, "%lluh ago",
1843 (unsigned long long) (d
/ USEC_PER_HOUR
));
1844 else if (d
>= USEC_PER_HOUR
)
1845 snprintf(buf
, l
, "%lluh %llumin ago",
1846 (unsigned long long) (d
/ USEC_PER_HOUR
),
1847 (unsigned long long) ((d
% USEC_PER_HOUR
) / USEC_PER_MINUTE
));
1848 else if (d
>= 5*USEC_PER_MINUTE
)
1849 snprintf(buf
, l
, "%llumin ago",
1850 (unsigned long long) (d
/ USEC_PER_MINUTE
));
1851 else if (d
>= USEC_PER_MINUTE
)
1852 snprintf(buf
, l
, "%llumin %llus ago",
1853 (unsigned long long) (d
/ USEC_PER_MINUTE
),
1854 (unsigned long long) ((d
% USEC_PER_MINUTE
) / USEC_PER_SEC
));
1855 else if (d
>= USEC_PER_SEC
)
1856 snprintf(buf
, l
, "%llus ago",
1857 (unsigned long long) (d
/ USEC_PER_SEC
));
1858 else if (d
>= USEC_PER_MSEC
)
1859 snprintf(buf
, l
, "%llums ago",
1860 (unsigned long long) (d
/ USEC_PER_MSEC
));
1862 snprintf(buf
, l
, "%lluus ago",
1863 (unsigned long long) d
);
1865 snprintf(buf
, l
, "now");
1871 char *format_timespan(char *buf
, size_t l
, usec_t t
) {
1872 static const struct {
1876 { "w", USEC_PER_WEEK
},
1877 { "d", USEC_PER_DAY
},
1878 { "h", USEC_PER_HOUR
},
1879 { "min", USEC_PER_MINUTE
},
1880 { "s", USEC_PER_SEC
},
1881 { "ms", USEC_PER_MSEC
},
1891 if (t
== (usec_t
) -1)
1895 snprintf(p
, l
, "0");
1900 /* The result of this function can be parsed with parse_usec */
1902 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
1906 if (t
< table
[i
].usec
)
1912 k
= snprintf(p
, l
, "%s%llu%s", p
> buf
? " " : "", (unsigned long long) (t
/ table
[i
].usec
), table
[i
].suffix
);
1913 n
= MIN((size_t) k
, l
);
1926 bool fstype_is_network(const char *fstype
) {
1927 static const char * const table
[] = {
1939 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
1940 if (streq(table
[i
], fstype
))
1949 if ((fd
= open("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
)) < 0)
1954 TIOCL_GETKMSGREDIRECT
,
1958 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0)
1961 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
1964 if (ioctl(fd
, VT_ACTIVATE
, vt
) < 0)
1967 close_nointr_nofail(r
);
1971 int read_one_char(FILE *f
, char *ret
, bool *need_nl
) {
1972 struct termios old_termios
, new_termios
;
1979 if (tcgetattr(fileno(f
), &old_termios
) >= 0) {
1980 new_termios
= old_termios
;
1982 new_termios
.c_lflag
&= ~ICANON
;
1983 new_termios
.c_cc
[VMIN
] = 1;
1984 new_termios
.c_cc
[VTIME
] = 0;
1986 if (tcsetattr(fileno(f
), TCSADRAIN
, &new_termios
) >= 0) {
1989 k
= fread(&c
, 1, 1, f
);
1991 tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
1997 *need_nl
= c
!= '\n';
2004 if (!(fgets(line
, sizeof(line
), f
)))
2009 if (strlen(line
) != 1)
2019 int ask(char *ret
, const char *replies
, const char *text
, ...) {
2026 on_tty
= isatty(STDOUT_FILENO
);
2032 bool need_nl
= true;
2035 fputs("\x1B[1m", stdout
);
2042 fputs("\x1B[0m", stdout
);
2046 if ((r
= read_one_char(stdin
, &c
, &need_nl
)) < 0) {
2048 if (r
== -EBADMSG
) {
2049 puts("Bad input, please try again.");
2060 if (strchr(replies
, c
)) {
2065 puts("Read unexpected character, please try again.");
2069 int reset_terminal(int fd
) {
2070 struct termios termios
;
2074 /* Set terminal to some sane defaults */
2078 /* We leave locked terminal attributes untouched, so that
2079 * Plymouth may set whatever it wants to set, and we don't
2080 * interfere with that. */
2082 /* Disable exclusive mode, just in case */
2083 ioctl(fd
, TIOCNXCL
);
2085 /* Enable console unicode mode */
2087 ioctl(fd
, KDSKBMODE
, &arg
);
2089 if (tcgetattr(fd
, &termios
) < 0) {
2094 /* We only reset the stuff that matters to the software. How
2095 * hardware is set up we don't touch assuming that somebody
2096 * else will do that for us */
2098 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
2099 termios
.c_iflag
|= ICRNL
| IMAXBEL
| IUTF8
;
2100 termios
.c_oflag
|= ONLCR
;
2101 termios
.c_cflag
|= CREAD
;
2102 termios
.c_lflag
= ISIG
| ICANON
| IEXTEN
| ECHO
| ECHOE
| ECHOK
| ECHOCTL
| ECHOPRT
| ECHOKE
;
2104 termios
.c_cc
[VINTR
] = 03; /* ^C */
2105 termios
.c_cc
[VQUIT
] = 034; /* ^\ */
2106 termios
.c_cc
[VERASE
] = 0177;
2107 termios
.c_cc
[VKILL
] = 025; /* ^X */
2108 termios
.c_cc
[VEOF
] = 04; /* ^D */
2109 termios
.c_cc
[VSTART
] = 021; /* ^Q */
2110 termios
.c_cc
[VSTOP
] = 023; /* ^S */
2111 termios
.c_cc
[VSUSP
] = 032; /* ^Z */
2112 termios
.c_cc
[VLNEXT
] = 026; /* ^V */
2113 termios
.c_cc
[VWERASE
] = 027; /* ^W */
2114 termios
.c_cc
[VREPRINT
] = 022; /* ^R */
2115 termios
.c_cc
[VEOL
] = 0;
2116 termios
.c_cc
[VEOL2
] = 0;
2118 termios
.c_cc
[VTIME
] = 0;
2119 termios
.c_cc
[VMIN
] = 1;
2121 if (tcsetattr(fd
, TCSANOW
, &termios
) < 0)
2125 /* Just in case, flush all crap out */
2126 tcflush(fd
, TCIOFLUSH
);
2131 int open_terminal(const char *name
, int mode
) {
2134 if ((fd
= open(name
, mode
)) < 0)
2137 if ((r
= isatty(fd
)) < 0) {
2138 close_nointr_nofail(fd
);
2143 close_nointr_nofail(fd
);
2150 int flush_fd(int fd
) {
2151 struct pollfd pollfd
;
2155 pollfd
.events
= POLLIN
;
2162 if ((r
= poll(&pollfd
, 1, 0)) < 0) {
2173 if ((l
= read(fd
, buf
, sizeof(buf
))) < 0) {
2178 if (errno
== EAGAIN
)
2189 int acquire_terminal(const char *name
, bool fail
, bool force
, bool ignore_tiocstty_eperm
) {
2190 int fd
= -1, notify
= -1, r
, wd
= -1;
2194 /* We use inotify to be notified when the tty is closed. We
2195 * create the watch before checking if we can actually acquire
2196 * it, so that we don't lose any event.
2198 * Note: strictly speaking this actually watches for the
2199 * device being closed, it does *not* really watch whether a
2200 * tty loses its controlling process. However, unless some
2201 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2202 * its tty otherwise this will not become a problem. As long
2203 * as the administrator makes sure not configure any service
2204 * on the same tty as an untrusted user this should not be a
2205 * problem. (Which he probably should not do anyway.) */
2207 if (!fail
&& !force
) {
2208 if ((notify
= inotify_init1(IN_CLOEXEC
)) < 0) {
2213 if ((wd
= inotify_add_watch(notify
, name
, IN_CLOSE
)) < 0) {
2221 if ((r
= flush_fd(notify
)) < 0)
2224 /* We pass here O_NOCTTY only so that we can check the return
2225 * value TIOCSCTTY and have a reliable way to figure out if we
2226 * successfully became the controlling process of the tty */
2227 if ((fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
)) < 0)
2230 /* First, try to get the tty */
2231 r
= ioctl(fd
, TIOCSCTTY
, force
);
2233 /* Sometimes it makes sense to ignore TIOCSCTTY
2234 * returning EPERM, i.e. when very likely we already
2235 * are have this controlling terminal. */
2236 if (r
< 0 && errno
== EPERM
&& ignore_tiocstty_eperm
)
2239 if (r
< 0 && (force
|| fail
|| errno
!= EPERM
)) {
2249 assert(notify
>= 0);
2252 uint8_t inotify_buffer
[sizeof(struct inotify_event
) + FILENAME_MAX
];
2254 struct inotify_event
*e
;
2256 if ((l
= read(notify
, &inotify_buffer
, sizeof(inotify_buffer
))) < 0) {
2265 e
= (struct inotify_event
*) inotify_buffer
;
2270 if (e
->wd
!= wd
|| !(e
->mask
& IN_CLOSE
)) {
2275 step
= sizeof(struct inotify_event
) + e
->len
;
2276 assert(step
<= (size_t) l
);
2278 e
= (struct inotify_event
*) ((uint8_t*) e
+ step
);
2285 /* We close the tty fd here since if the old session
2286 * ended our handle will be dead. It's important that
2287 * we do this after sleeping, so that we don't enter
2288 * an endless loop. */
2289 close_nointr_nofail(fd
);
2293 close_nointr_nofail(notify
);
2295 if ((r
= reset_terminal(fd
)) < 0)
2296 log_warning("Failed to reset terminal: %s", strerror(-r
));
2302 close_nointr_nofail(fd
);
2305 close_nointr_nofail(notify
);
2310 int release_terminal(void) {
2312 struct sigaction sa_old
, sa_new
;
2314 if ((fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_NDELAY
)) < 0)
2317 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2318 * by our own TIOCNOTTY */
2321 sa_new
.sa_handler
= SIG_IGN
;
2322 sa_new
.sa_flags
= SA_RESTART
;
2323 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
2325 if (ioctl(fd
, TIOCNOTTY
) < 0)
2328 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
2330 close_nointr_nofail(fd
);
2334 int sigaction_many(const struct sigaction
*sa
, ...) {
2339 while ((sig
= va_arg(ap
, int)) > 0)
2340 if (sigaction(sig
, sa
, NULL
) < 0)
2347 int ignore_signals(int sig
, ...) {
2348 struct sigaction sa
;
2353 sa
.sa_handler
= SIG_IGN
;
2354 sa
.sa_flags
= SA_RESTART
;
2356 if (sigaction(sig
, &sa
, NULL
) < 0)
2360 while ((sig
= va_arg(ap
, int)) > 0)
2361 if (sigaction(sig
, &sa
, NULL
) < 0)
2368 int default_signals(int sig
, ...) {
2369 struct sigaction sa
;
2374 sa
.sa_handler
= SIG_DFL
;
2375 sa
.sa_flags
= SA_RESTART
;
2377 if (sigaction(sig
, &sa
, NULL
) < 0)
2381 while ((sig
= va_arg(ap
, int)) > 0)
2382 if (sigaction(sig
, &sa
, NULL
) < 0)
2389 int close_pipe(int p
[]) {
2395 a
= close_nointr(p
[0]);
2400 b
= close_nointr(p
[1]);
2404 return a
< 0 ? a
: b
;
2407 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2416 while (nbytes
> 0) {
2419 if ((k
= read(fd
, p
, nbytes
)) <= 0) {
2421 if (k
< 0 && errno
== EINTR
)
2424 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2425 struct pollfd pollfd
;
2429 pollfd
.events
= POLLIN
;
2431 if (poll(&pollfd
, 1, -1) < 0) {
2435 return n
> 0 ? n
: -errno
;
2438 if (pollfd
.revents
!= POLLIN
)
2439 return n
> 0 ? n
: -EIO
;
2444 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2455 ssize_t
loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2464 while (nbytes
> 0) {
2467 if ((k
= write(fd
, p
, nbytes
)) <= 0) {
2469 if (k
< 0 && errno
== EINTR
)
2472 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2473 struct pollfd pollfd
;
2477 pollfd
.events
= POLLOUT
;
2479 if (poll(&pollfd
, 1, -1) < 0) {
2483 return n
> 0 ? n
: -errno
;
2486 if (pollfd
.revents
!= POLLOUT
)
2487 return n
> 0 ? n
: -EIO
;
2492 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2503 int path_is_mount_point(const char *t
) {
2508 if (lstat(t
, &a
) < 0) {
2509 if (errno
== ENOENT
)
2515 if ((r
= parent_of_path(t
, &parent
)) < 0)
2518 r
= lstat(parent
, &b
);
2524 return a
.st_dev
!= b
.st_dev
;
2527 int parse_usec(const char *t
, usec_t
*usec
) {
2528 static const struct {
2532 { "sec", USEC_PER_SEC
},
2533 { "s", USEC_PER_SEC
},
2534 { "min", USEC_PER_MINUTE
},
2535 { "hr", USEC_PER_HOUR
},
2536 { "h", USEC_PER_HOUR
},
2537 { "d", USEC_PER_DAY
},
2538 { "w", USEC_PER_WEEK
},
2539 { "msec", USEC_PER_MSEC
},
2540 { "ms", USEC_PER_MSEC
},
2541 { "m", USEC_PER_MINUTE
},
2544 { "", USEC_PER_SEC
},
2560 l
= strtoll(p
, &e
, 10);
2571 e
+= strspn(e
, WHITESPACE
);
2573 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
2574 if (startswith(e
, table
[i
].suffix
)) {
2575 r
+= (usec_t
) l
* table
[i
].usec
;
2576 p
= e
+ strlen(table
[i
].suffix
);
2580 if (i
>= ELEMENTSOF(table
))
2590 int make_stdio(int fd
) {
2595 r
= dup2(fd
, STDIN_FILENO
);
2596 s
= dup2(fd
, STDOUT_FILENO
);
2597 t
= dup2(fd
, STDERR_FILENO
);
2600 close_nointr_nofail(fd
);
2602 if (r
< 0 || s
< 0 || t
< 0)
2608 int make_null_stdio(void) {
2611 if ((null_fd
= open("/dev/null", O_RDWR
|O_NOCTTY
)) < 0)
2614 return make_stdio(null_fd
);
2617 bool is_clean_exit(int code
, int status
) {
2619 if (code
== CLD_EXITED
)
2622 /* If a daemon does not implement handlers for some of the
2623 * signals that's not considered an unclean shutdown */
2624 if (code
== CLD_KILLED
)
2628 status
== SIGTERM
||
2634 bool is_clean_exit_lsb(int code
, int status
) {
2636 if (is_clean_exit(code
, status
))
2640 code
== CLD_EXITED
&&
2641 (status
== EXIT_NOTINSTALLED
|| status
== EXIT_NOTCONFIGURED
);
2644 bool is_device_path(const char *path
) {
2646 /* Returns true on paths that refer to a device, either in
2647 * sysfs or in /dev */
2650 path_startswith(path
, "/dev/") ||
2651 path_startswith(path
, "/sys/");
2654 int dir_is_empty(const char *path
) {
2657 struct dirent buf
, *de
;
2659 if (!(d
= opendir(path
)))
2663 if ((r
= readdir_r(d
, &buf
, &de
)) > 0) {
2673 if (!ignore_file(de
->d_name
)) {
2683 unsigned long long random_ull(void) {
2688 if ((fd
= open("/dev/urandom", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
)) < 0)
2691 r
= loop_read(fd
, &ull
, sizeof(ull
), true);
2692 close_nointr_nofail(fd
);
2694 if (r
!= sizeof(ull
))
2700 return random() * RAND_MAX
+ random();
2703 void rename_process(const char name
[8]) {
2706 prctl(PR_SET_NAME
, name
);
2708 /* This is a like a poor man's setproctitle(). The string
2709 * passed should fit in 7 chars (i.e. the length of
2712 if (program_invocation_name
)
2713 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2716 void sigset_add_many(sigset_t
*ss
, ...) {
2723 while ((sig
= va_arg(ap
, int)) > 0)
2724 assert_se(sigaddset(ss
, sig
) == 0);
2728 char* gethostname_malloc(void) {
2731 assert_se(uname(&u
) >= 0);
2734 return strdup(u
.nodename
);
2736 return strdup(u
.sysname
);
2739 char* getlogname_malloc(void) {
2743 struct passwd pwbuf
, *pw
= NULL
;
2746 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2751 /* Shortcut things to avoid NSS lookups */
2753 return strdup("root");
2755 if ((bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
)) <= 0)
2758 if (!(buf
= malloc(bufsize
)))
2761 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
) {
2762 name
= strdup(pw
->pw_name
);
2769 if (asprintf(&name
, "%lu", (unsigned long) uid
) < 0)
2775 int getttyname_malloc(char **r
) {
2776 char path
[PATH_MAX
], *p
, *c
;
2781 if ((k
= ttyname_r(STDIN_FILENO
, path
, sizeof(path
))) != 0)
2787 if (startswith(path
, "/dev/"))
2790 if (!(c
= strdup(p
)))
2797 static int rm_rf_children(int fd
, bool only_dirs
) {
2803 /* This returns the first error we run into, but nevertheless
2806 if (!(d
= fdopendir(fd
))) {
2807 close_nointr_nofail(fd
);
2809 return errno
== ENOENT
? 0 : -errno
;
2813 struct dirent buf
, *de
;
2817 if ((r
= readdir_r(d
, &buf
, &de
)) != 0) {
2826 if (streq(de
->d_name
, ".") || streq(de
->d_name
, ".."))
2829 if (de
->d_type
== DT_UNKNOWN
) {
2832 if (fstatat(fd
, de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0) {
2833 if (ret
== 0 && errno
!= ENOENT
)
2838 is_dir
= S_ISDIR(st
.st_mode
);
2840 is_dir
= de
->d_type
== DT_DIR
;
2845 if ((subdir_fd
= openat(fd
, de
->d_name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
)) < 0) {
2846 if (ret
== 0 && errno
!= ENOENT
)
2851 if ((r
= rm_rf_children(subdir_fd
, only_dirs
)) < 0) {
2856 if (unlinkat(fd
, de
->d_name
, AT_REMOVEDIR
) < 0) {
2857 if (ret
== 0 && errno
!= ENOENT
)
2860 } else if (!only_dirs
) {
2862 if (unlinkat(fd
, de
->d_name
, 0) < 0) {
2863 if (ret
== 0 && errno
!= ENOENT
)
2874 int rm_rf(const char *path
, bool only_dirs
, bool delete_root
) {
2880 if ((fd
= open(path
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
)) < 0) {
2882 if (errno
!= ENOTDIR
)
2885 if (delete_root
&& !only_dirs
)
2886 if (unlink(path
) < 0)
2892 r
= rm_rf_children(fd
, only_dirs
);
2895 if (rmdir(path
) < 0) {
2903 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2906 /* Under the assumption that we are running privileged we
2907 * first change the access mode and only then hand out
2908 * ownership to avoid a window where access is too open. */
2910 if (chmod(path
, mode
) < 0)
2913 if (chown(path
, uid
, gid
) < 0)
2919 cpu_set_t
* cpu_set_malloc(unsigned *ncpus
) {
2923 /* Allocates the cpuset in the right size */
2926 if (!(r
= CPU_ALLOC(n
)))
2929 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), r
) >= 0) {
2930 CPU_ZERO_S(CPU_ALLOC_SIZE(n
), r
);
2940 if (errno
!= EINVAL
)
2947 void status_vprintf(const char *format
, va_list ap
) {
2953 /* This independent of logging, as status messages are
2954 * optional and go exclusively to the console. */
2956 if (vasprintf(&s
, format
, ap
) < 0)
2959 if ((fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
)) < 0)
2962 write(fd
, s
, strlen(s
));
2968 close_nointr_nofail(fd
);
2971 void status_printf(const char *format
, ...) {
2976 va_start(ap
, format
);
2977 status_vprintf(format
, ap
);
2981 void status_welcome(void) {
2983 #if defined(TARGET_FEDORA)
2986 if (read_one_line_file("/etc/system-release", &r
) < 0)
2991 /* This tries to mimic the color magic the old Red Hat sysinit
2994 if (startswith(r
, "Red Hat"))
2995 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r
); /* Red for RHEL */
2996 else if (startswith(r
, "Fedora"))
2997 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r
); /* Blue for Fedora */
2999 status_printf("Welcome to %s!\n", r
);
3003 #elif defined(TARGET_SUSE)
3006 if (read_one_line_file("/etc/SuSE-release", &r
) < 0)
3011 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r
); /* Green for SUSE */
3014 #elif defined(TARGET_GENTOO)
3017 if (read_one_line_file("/etc/gentoo-release", &r
) < 0)
3022 status_printf("Welcome to \x1B[1;34m%s\x1B[0m!\n", r
); /* Light Blue for Gentoo */
3026 #elif defined(TARGET_DEBIAN)
3029 if (read_one_line_file("/etc/debian_version", &r
) < 0)
3034 status_printf("Welcome to Debian \x1B[1;31m%s\x1B[0m!\n", r
); /* Light Red for Debian */
3037 #elif defined(TARGET_UBUNTU)
3039 char *codename
= NULL
;
3041 if (parse_env_file("/etc/lsb-release", NEWLINE
,
3042 "DISTRIB_DESCRIPTION", &desc
,
3043 "DISTRIB_CODENAME", &codename
, NULL
) < 0)
3045 if (desc
&& codename
)
3046 /* Light Red for Ubuntu */
3047 status_printf("Welcome to \x1B[1;31m%s\x1B[0m (%s)\n",
3051 #elif defined(TARGET_ARCH)
3052 status_printf("Welcome to \x1B[1;36mArch Linux\x1B[0m!\n"); /* Cyan for Arch */
3054 #warning "You probably should add a welcome text logic here."
3058 char *replace_env(const char *format
, char **env
) {
3065 const char *e
, *word
= format
;
3070 for (e
= format
; *e
; e
++) {
3081 if (!(k
= strnappend(r
, word
, e
-word
-1)))
3090 } else if (*e
== '$') {
3091 if (!(k
= strnappend(r
, word
, e
-word
)))
3107 if (!(t
= strv_env_get_with_length(env
, word
+2, e
-word
-2)))
3110 if (!(k
= strappend(r
, t
)))
3123 if (!(k
= strnappend(r
, word
, e
-word
)))
3134 char **replace_env_argv(char **argv
, char **env
) {
3136 unsigned k
= 0, l
= 0;
3138 l
= strv_length(argv
);
3140 if (!(r
= new(char*, l
+1)))
3143 STRV_FOREACH(i
, argv
) {
3145 /* If $FOO appears as single word, replace it by the split up variable */
3146 if ((*i
)[0] == '$' && (*i
)[1] != '{') {
3151 if ((e
= strv_env_get(env
, *i
+1))) {
3153 if (!(m
= strv_split_quoted(e
))) {
3164 if (!(w
= realloc(r
, sizeof(char*) * (l
+1)))) {
3173 memcpy(r
+ k
, m
, q
* sizeof(char*));
3181 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3182 if (!(r
[k
++] = replace_env(*i
, env
))) {
3193 static __thread
int parsed_columns
= 0;
3196 if (parsed_columns
> 0)
3197 return parsed_columns
;
3199 if ((e
= getenv("COLUMNS")))
3200 parsed_columns
= atoi(e
);
3202 if (parsed_columns
<= 0) {
3206 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &ws
) >= 0)
3207 parsed_columns
= ws
.ws_col
;
3210 if (parsed_columns
<= 0)
3211 parsed_columns
= 80;
3213 return parsed_columns
;
3216 int running_in_chroot(void) {
3222 /* Only works as root */
3224 if (stat("/proc/1/root", &a
) < 0)
3227 if (stat("/", &b
) < 0)
3231 a
.st_dev
!= b
.st_dev
||
3232 a
.st_ino
!= b
.st_ino
;
3235 char *ellipsize(const char *s
, unsigned length
, unsigned percent
) {
3240 assert(percent
<= 100);
3241 assert(length
>= 3);
3245 if (l
<= 3 || l
<= length
)
3248 if (!(r
= new0(char, length
+1)))
3251 x
= (length
* percent
) / 100;
3261 s
+ l
- (length
- x
- 3),
3267 int touch(const char *path
) {
3272 if ((fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, 0666)) < 0)
3275 close_nointr_nofail(fd
);
3279 char *unquote(const char *s
, const char* quotes
) {
3283 if ((l
= strlen(s
)) < 2)
3286 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
3287 return strndup(s
+1, l
-2);
3292 int wait_for_terminate(pid_t pid
, siginfo_t
*status
) {
3299 if (waitid(P_PID
, pid
, status
, WEXITED
) < 0) {
3311 int wait_for_terminate_and_warn(const char *name
, pid_t pid
) {
3318 if ((r
= wait_for_terminate(pid
, &status
)) < 0) {
3319 log_warning("Failed to wait for %s: %s", name
, strerror(-r
));
3323 if (status
.si_code
== CLD_EXITED
) {
3324 if (status
.si_status
!= 0) {
3325 log_warning("%s failed with error code %i.", name
, status
.si_status
);
3329 log_debug("%s succeeded.", name
);
3332 } else if (status
.si_code
== CLD_KILLED
||
3333 status
.si_code
== CLD_DUMPED
) {
3335 log_warning("%s terminated by signal %s.", name
, signal_to_string(status
.si_status
));
3339 log_warning("%s failed due to unknown reason.", name
);
3349 bool null_or_empty(struct stat
*st
) {
3352 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
3355 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
3361 DIR *xopendirat(int fd
, const char *name
) {
3362 return fdopendir(openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
));
3365 int signal_from_string_try_harder(const char *s
) {
3369 if ((signo
= signal_from_string(s
)) <= 0)
3370 if (startswith(s
, "SIG"))
3371 return signal_from_string(s
+3);
3376 int ask_password_tty(const char *message
, usec_t until
, const char *flag_file
, char **_passphrase
) {
3377 struct termios old_termios
, new_termios
;
3378 char passphrase
[LINE_MAX
];
3380 int r
, ttyfd
= -1, notify
= -1;
3381 struct pollfd pollfd
[2];
3382 bool reset_tty
= false;
3389 assert(_passphrase
);
3392 if ((notify
= inotify_init1(IN_CLOEXEC
|IN_NONBLOCK
)) < 0) {
3397 if (inotify_add_watch(notify
, flag_file
, IN_ATTRIB
/* for the link count */) < 0) {
3403 if ((ttyfd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
)) >= 0) {
3405 if (tcgetattr(ttyfd
, &old_termios
) < 0) {
3410 loop_write(ttyfd
, "\x1B[1m", 4, false);
3411 loop_write(ttyfd
, message
, strlen(message
), false);
3412 loop_write(ttyfd
, ": ", 2, false);
3413 loop_write(ttyfd
, "\x1B[0m", 4, false);
3415 new_termios
= old_termios
;
3416 new_termios
.c_lflag
&= ~(ICANON
|ECHO
);
3417 new_termios
.c_cc
[VMIN
] = 1;
3418 new_termios
.c_cc
[VTIME
] = 0;
3420 if (tcsetattr(ttyfd
, TCSADRAIN
, &new_termios
) < 0) {
3430 pollfd
[POLL_TTY
].fd
= ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
;
3431 pollfd
[POLL_TTY
].events
= POLLIN
;
3432 pollfd
[POLL_INOTIFY
].fd
= notify
;
3433 pollfd
[POLL_INOTIFY
].events
= POLLIN
;
3437 int sleep_for
= -1, k
;
3443 y
= now(CLOCK_MONOTONIC
);
3450 sleep_for
= (int) ((until
- y
) / USEC_PER_MSEC
);
3454 if (access(flag_file
, F_OK
) < 0) {
3459 if ((k
= poll(pollfd
, notify
> 0 ? 2 : 1, sleep_for
)) < 0) {
3466 } else if (k
== 0) {
3471 if (notify
> 0 && pollfd
[POLL_INOTIFY
].revents
!= 0)
3474 if (pollfd
[POLL_TTY
].revents
== 0)
3477 if ((n
= read(ttyfd
>= 0 ? ttyfd
: STDIN_FILENO
, &c
, 1)) < 0) {
3479 if (errno
== EINTR
|| errno
== EAGAIN
)
3496 loop_write(ttyfd
, "\b \b", 3, false);
3499 } else if (c
== '\b' || c
== 127) {
3504 loop_write(ttyfd
, "\b \b", 3, false);
3507 passphrase
[p
++] = c
;
3510 loop_write(ttyfd
, "*", 1, false);
3515 loop_write(ttyfd
, "\n", 1, false);
3519 if (!(*_passphrase
= strdup(passphrase
))) {
3528 close_nointr_nofail(notify
);
3532 tcsetattr(ttyfd
, TCSADRAIN
, &old_termios
);
3534 close_nointr_nofail(ttyfd
);
3540 void dual_timestamp_serialize(FILE *f
, const char *name
, dual_timestamp
*t
) {
3546 if (!dual_timestamp_is_set(t
))
3549 fprintf(f
, "%s=%llu %llu\n",
3551 (unsigned long long) t
->realtime
,
3552 (unsigned long long) t
->monotonic
);
3555 void dual_timestamp_deserialize(const char *value
, dual_timestamp
*t
) {
3556 unsigned long long a
, b
;
3561 if (sscanf(value
, "%lli %llu", &a
, &b
) != 2)
3562 log_debug("Failed to parse finish timestamp value %s", value
);
3569 char *fstab_node_to_udev_node(const char *p
) {
3573 /* FIXME: to follow udev's logic 100% we need to leave valid
3574 * UTF8 chars unescaped */
3576 if (startswith(p
, "LABEL=")) {
3578 if (!(u
= unquote(p
+6, "\"\'")))
3581 t
= xescape(u
, "/ ");
3587 r
= asprintf(&dn
, "/dev/disk/by-label/%s", t
);
3596 if (startswith(p
, "UUID=")) {
3598 if (!(u
= unquote(p
+5, "\"\'")))
3601 t
= xescape(u
, "/ ");
3607 r
= asprintf(&dn
, "/dev/disk/by-uuid/%s", ascii_strlower(t
));
3619 void filter_environ(const char *prefix
) {
3626 for (i
= 0, j
= 0; environ
[i
]; i
++) {
3628 if (startswith(environ
[i
], prefix
))
3631 environ
[j
++] = environ
[i
];
3637 static const char *const ioprio_class_table
[] = {
3638 [IOPRIO_CLASS_NONE
] = "none",
3639 [IOPRIO_CLASS_RT
] = "realtime",
3640 [IOPRIO_CLASS_BE
] = "best-effort",
3641 [IOPRIO_CLASS_IDLE
] = "idle"
3644 DEFINE_STRING_TABLE_LOOKUP(ioprio_class
, int);
3646 static const char *const sigchld_code_table
[] = {
3647 [CLD_EXITED
] = "exited",
3648 [CLD_KILLED
] = "killed",
3649 [CLD_DUMPED
] = "dumped",
3650 [CLD_TRAPPED
] = "trapped",
3651 [CLD_STOPPED
] = "stopped",
3652 [CLD_CONTINUED
] = "continued",
3655 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
3657 static const char *const log_facility_table
[LOG_NFACILITIES
] = {
3658 [LOG_FAC(LOG_KERN
)] = "kern",
3659 [LOG_FAC(LOG_USER
)] = "user",
3660 [LOG_FAC(LOG_MAIL
)] = "mail",
3661 [LOG_FAC(LOG_DAEMON
)] = "daemon",
3662 [LOG_FAC(LOG_AUTH
)] = "auth",
3663 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
3664 [LOG_FAC(LOG_LPR
)] = "lpr",
3665 [LOG_FAC(LOG_NEWS
)] = "news",
3666 [LOG_FAC(LOG_UUCP
)] = "uucp",
3667 [LOG_FAC(LOG_CRON
)] = "cron",
3668 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
3669 [LOG_FAC(LOG_FTP
)] = "ftp",
3670 [LOG_FAC(LOG_LOCAL0
)] = "local0",
3671 [LOG_FAC(LOG_LOCAL1
)] = "local1",
3672 [LOG_FAC(LOG_LOCAL2
)] = "local2",
3673 [LOG_FAC(LOG_LOCAL3
)] = "local3",
3674 [LOG_FAC(LOG_LOCAL4
)] = "local4",
3675 [LOG_FAC(LOG_LOCAL5
)] = "local5",
3676 [LOG_FAC(LOG_LOCAL6
)] = "local6",
3677 [LOG_FAC(LOG_LOCAL7
)] = "local7"
3680 DEFINE_STRING_TABLE_LOOKUP(log_facility
, int);
3682 static const char *const log_level_table
[] = {
3683 [LOG_EMERG
] = "emerg",
3684 [LOG_ALERT
] = "alert",
3685 [LOG_CRIT
] = "crit",
3687 [LOG_WARNING
] = "warning",
3688 [LOG_NOTICE
] = "notice",
3689 [LOG_INFO
] = "info",
3690 [LOG_DEBUG
] = "debug"
3693 DEFINE_STRING_TABLE_LOOKUP(log_level
, int);
3695 static const char* const sched_policy_table
[] = {
3696 [SCHED_OTHER
] = "other",
3697 [SCHED_BATCH
] = "batch",
3698 [SCHED_IDLE
] = "idle",
3699 [SCHED_FIFO
] = "fifo",
3703 DEFINE_STRING_TABLE_LOOKUP(sched_policy
, int);
3705 static const char* const rlimit_table
[] = {
3706 [RLIMIT_CPU
] = "LimitCPU",
3707 [RLIMIT_FSIZE
] = "LimitFSIZE",
3708 [RLIMIT_DATA
] = "LimitDATA",
3709 [RLIMIT_STACK
] = "LimitSTACK",
3710 [RLIMIT_CORE
] = "LimitCORE",
3711 [RLIMIT_RSS
] = "LimitRSS",
3712 [RLIMIT_NOFILE
] = "LimitNOFILE",
3713 [RLIMIT_AS
] = "LimitAS",
3714 [RLIMIT_NPROC
] = "LimitNPROC",
3715 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
3716 [RLIMIT_LOCKS
] = "LimitLOCKS",
3717 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
3718 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
3719 [RLIMIT_NICE
] = "LimitNICE",
3720 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
3721 [RLIMIT_RTTIME
] = "LimitRTTIME"
3724 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
3726 static const char* const ip_tos_table
[] = {
3727 [IPTOS_LOWDELAY
] = "low-delay",
3728 [IPTOS_THROUGHPUT
] = "throughput",
3729 [IPTOS_RELIABILITY
] = "reliability",
3730 [IPTOS_LOWCOST
] = "low-cost",
3733 DEFINE_STRING_TABLE_LOOKUP(ip_tos
, int);
3735 static const char *const signal_table
[] = {
3752 [SIGSTKFLT
] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3763 [SIGVTALRM
] = "VTALRM",
3765 [SIGWINCH
] = "WINCH",
3771 DEFINE_STRING_TABLE_LOOKUP(signal
, int);